0

the exercise has you build two subroutines.. &average (which computes the average of a list of numbers) and &above_average (which will print out the numbers in the list that are greater than the average).

The answer they give for the above_average sub is:

sub above_average
{ my $average = average(@_);
  my @list;
 foreach my $element (@_) {
 if ($element > $average ){
    push @list, $element;
    }
   }
 @list;
}

And the accompanying text asks "Why is the control variable $element used instead of Perl's favorite default $_?"

Why is that? I actually wrote my answer using $_ and it seemed to work.. so I'm curious why the author feels the need to highlight that he used $element instead of $_.

Thanks!

  • 1
    This post is also very informative on the subject: http://www.perlmonks.org/?node_id=641994 – scrappedcola Nov 01 '13 at 20:40
  • 1
    5th Edition? The latest I have (and the latest shown [here](http://shop.oreilly.com/product/9780596004927.do)) is the 4th edition. – Keith Thompson Nov 01 '13 at 21:01
  • Thanks, I'll check out those other posts – user2434008 Nov 01 '13 at 21:27
  • Keith.. I think they are actually up to a 6th edition now.. http://shop.oreilly.com/product/0636920018452.do – user2434008 Nov 01 '13 at 21:28
  • In this particular example, there is no reason to prefer one over the other. Alternatively, you can use any excuse you like to prefer one over the other. – runrig Nov 02 '13 at 00:21
  • 1
    The book you are talking about is `Learning Perl` not `Programming Perl`. In this particular example I think the emphasis is more on readability rather than functionality. – edi_allen Nov 02 '13 at 00:53

0 Answers0