Rob Dixon 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?

Every function/subroutine has overhead, set up the stack, create lexical scope, etc. so calling print() once with a list is more efficient then calling print() N times in a foreach loop.


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;

(It also doesn't print a terminating "\n")

That could be fixed thusly:

    print map {$_ % 2 == 0 ? "$_\n" : ()} @list;

Although this would probably be more efficient:

    print map $_ & 1 ? () : "$_\n", @list;




John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order.                            -- Larry Wall

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


Reply via email to