This came up somewhere else, people disagreed and now I can't see it
clearly anymore. Imagine you have an array filled with numbers, and
you only want to print out the even ones. Fine, someone says, use
grep.

print "$_\n" for grep {$_ % 2 == 0} @testAr;

But is this a void context? On the one hand you're not literally
throwing away the results, but on the other hand you're also not
looking to keep the list that grep builds itself. So in a sense, you
seem to be creating a list just to iterate over it in the print
statement. That seems to be what the Pelr FAQ has in mind here, "This
means you're making Perl go to the trouble of building a list that you
then just throw away. If the list is large, you waste both time and
space. If your intent is to iterate over the list, then use a for loop
for this purpose."

So in a context like this, would the following be better?

for my $num (@testAr) {
    if (($num % 2) == 0 ) {
        print "$num\n";
    }
}

So I guess my question is this: Does the FAQ (and advice like it) mean
to avoid using grep *unless* you actually want to keep and use the
list, or does it just mean don't use grep only for side effects?

Thanks in advance.


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to