in reply to Difference between foreach and grep

As the previous poster already said map and grep have similarities. But map and foreach also have similarities…silly transitive property…

A small blurb I copy/pasted from http://www.hidemail.de/blog/perl_tutor.shtml#map_grep_foreach (bolded by moi):

Map can select elements from an array, just like grep. The following two statements are equivalent (EXPR represents a logical expression).

@selected = grep EXPR, @input; @selected = map { if (EXPR) { $_ } } @input;

Also, map is just a special case of a foreach statement. The statement:

@transformed = map EXPR, @input;

(where EXPR is some expression containing $_) is equivalent to (if @transformed is undefined or empty):

foreach (@input) { push @transformed, EXPR; }

In general, use grep to select elements from an array and map to transform the elements of an array. Other array processing can be done with one of the loop statements (foreach, for, while, until, do while, do until, redo). Avoid using statements in grep/map blocks that do not affect the grep/map results; moving these "side-effect" statements to a loop makes your code more readable and cohesive.

I'm so adjective, I verb nouns!

chomp; # nom nom nom

Replies are listed 'Best First'.
Re^2: Difference between foreach and grep
by kyle (Abbot) on Dec 06, 2008 at 14:31 UTC

    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 = [];
Re^2: Difference between foreach and grep
by chromatic (Archbishop) on Dec 06, 2008 at 09:03 UTC
    map is just a special case of a foreach statement....

    How do you figure, because they both operate on a list? Is sum a special case of a for? foldl? foldr?

Re^2: Difference between foreach and grep
by Anonymous Monk on Dec 06, 2008 at 04:59 UTC
    Dear Monk, I referred the link, it gives enough vision. Thanks