On Nov 19, 2007 8:37 PM, Telemachus Odysseos <[EMAIL PROTECTED]> wrote: > Maybe a better title is "A question about the comments on one of the answers > to an exercise." Anyhow, this seems like a reasonable place to ask. I just > finished doing the exercises for chapter 4 in the Llama book (on > subroutines) and for question 3, I produced this for a subroutine to collect > numbers above an average: > > sub above_average { > my $average = &average(@_); > my @above_average; > foreach (@_) { > if ($_ > $average) { > push @above_average, $_; > } > } > return @above_average; > } > > In the answer the foreach block has $element in place of $_, and the text > specifically asks, "Why is the control variable named $element instead of > using Perl's favorite default, $_?" So, I'm stumped - Why should it be > $element instead of $_? My version appears to work well (I even tested with > other values for the number groups), but maybe there is some potential > breakage I'm not seeing. > > Thanks in advance, Telemachus >
There is nothing wrong with you usage, but there are at least three reasons to prefer a named variable 1. the default variable can be set or masked by other constructs 2. in long pieces of code it is easier to remember what that variables purpose is 3. you may already be using $_ to hold something you want to reference in the loop Take a look at this for (1 .. 3) { for (1 .. 3) { print "$_ * $_ = ", $_*$_, "\n"; } } versus this for my $m (1 .. 3) { for my $n (1 .. 3) { print "$m * $n = ", $m*$n, "\n"; } } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/