On Tue, Mar 25, 2008 at 11:00 PM, Telemachus <[EMAIL PROTECTED]> wrote: > 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. >
No, you're using grep in list context. You *are* keeping the results (from grep's perspective): you're passing the result list to for. Remember, though, that grep evaluates the code in the block, once for each time through the list, so in theory, you could do things like: grep {print "$_\n"} 0..1000; grep {$count++ if $_ % 2 == 0} 0..1000; grep {$_++} @nums; In these examples, we really are just ignoring the return value of grep entirely; that is what the docs mean by using grep in a void context. Don't do that. grep spends memory and processor cycles building up the result list; don't waste those resources if you don't need the results. If all you want to do is iterate through a list and do something with each of the elements, there are other, more efficient, ways to do that. The examples above could be better solved by while loops, or map, depending on the context. In your case, though, you really do need the results to pass to for, so grep is the correct tool. HTH, -- jay -------------------------------------------------- This email and attachment(s): [ ] blogable; [ x ] ask first; [ ] private and confidential daggerquill [at] gmail [dot] com http://www.tuaw.com http://www.downloadsquad.com http://www.engatiki.org values of β will give rise to dom!