On Wed, Mar 26, 2008 at 9:47 PM, Rob Dixon <[EMAIL PROTECTED]> wrote: > Jay Savage wrote: > > > > 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; > > I think that's very misleading. Why should I want to avoid calling print > for each element? What you've written is the sort of thing for which > Perl gets a bad name - it's less readable and has no obvious benefits > over > > print "$_\n" foreach grep { $_ % 2 == 0 } @list; >
cmpthese(1000, { 'foreach' => sub { print "$_\n" for grep {$_ % 2 == 0} 0..1000; }, 'join' => sub { print join "\n", grep {$_ % 2 == 0} 0..1000; }, }); Rate foreach join foreach 40.7/s -- -20% join 50.8/s 25% -- 25% performance gain strikes me as a pretty obvious benefit. YMMV, of course, depending on your data and memory performance, but in general, function calls are expensive, and and print moreso than most, because it requires a system call out to the OS. Calling a function like print on each iteration through a loop is rarely the most efficient way to do business. This doesn't really have anything to do with Perl; it's true in any language. Of course, efficiency, like beauty, is in the eye of the beholder. And that's why I was clear with OP, that he should do whatever made the most sense for him in his particular situation. TIMTOWTDI isn't what gives Perl a bad name; it's what makes it the wonderful, flexible tool that it is, and crates passionate groups of users like this one. > (It also doesn't print a terminating "\n") > I think you'll agree there are several trivial fixes for this. 'print "\n"' jumps immediately to mind. Best, -- 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!