in reply to Re: Difference between foreach and grep
in thread Difference between foreach and grep
The following two statements are equivalent (EXPR represents a logical expression).
@selected = grep EXPR, @input; @selected = map { if (EXPR) { $_ } } @input;
That's not really true. Your second one, for each element, will be either $_ (if EXPR is true) or EXPR if it's false. The usual way to make map like grep is with the ternary operator as below.
use Data::Dumper; my @x = qw( foo bar ); print q[ map { if (0) { $_ } } @x ], "\n"; print Dumper [ map { if (0) { $_ } } @x ]; print "\n", q[ grep 0, @x ], "\n"; print Dumper [ grep 0, @x ]; print "\n", q[ map { 0 ? $_ : () } @x ], "\n"; print Dumper [ map { 0 ? $_ : () } @x ]; __END__ map { if (0) { $_ } } @x $VAR1 = [ 0, 0 ]; grep 0, @x $VAR1 = []; map { 0 ? $_ : () } @x $VAR1 = [];
|
|---|