On Wed, Mar 26, 2008 at 9:10 AM, Telemachus <[EMAIL PROTECTED]> wrote: > On Mar 26, 8:24 am, [EMAIL PROTECTED] (John W. Krahn) wrote: > <snip> > > > Telemachus wrote: > > > So in a context like this, would the following be better? > > > > > for my $num (@testAr) { > > > if (($num % 2) == 0 ) { > > > print "$num\n"; > > > } > > > } > > > > That code is iterating over a larger list, assuming that @testAr > > contains *some* odd numbers. > > First, thanks for your response. This one bit confuses me: how is the > if iterating over a *larger* list than the grep? Don't they both have > to run through all of @testAr in order to weed out odd numbers? Is > there an advantage to using grep here rather than the foreach? >
Not a larger list than grep, a larger list than the list of even numbers. @list_list_of_all_numbers > @list_of_even_numbers. You want to do something (print) with only certain items from a list that meet certain criteria. That is what grep is designed to do, so grep is appropriate. This isn't a void context, because you are using the return value. See my earlier post for some examples of grep in a void context actually looks like. There is nothing wrong with using grep to feed a while loop. It's a convenient way to turn a multi-line block of code into a single conditional expression, as you've done. If you want to see grep really shine, though, think about ways you might use it to avoid calling print for every element in the return list, e.g. print join "\n", grep {$_ % 2 == 0} @list; What you are doing now isn't wrong, though, and using a plain foreach loop wouldn't be wrong, either. What works best for you will depend on how big the list is, how your system is configured, and, most importantly, what is more comfortable for you and easier on whoever will be maintaining your program. This is a clear case of the the Perl motto: There Is More Than One Way To Do It. 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!