in reply to Difference between foreach and grep

for/foreach is more like map than grep. foreach iterates over a list setting a loop variable as an alias to each element of the list in turn and executing a block of statements. In like fashion map iterates over a list setting a the default variable ($_) as an alias to each element of the list in turn and executing a block of statements. The difference between the two is that map returns a list containing the (probably modified) list of values.

grep iterates over a list setting a the default variable ($_) as an alias to each element of the list in turn and executing a block of statements. grep returns a list containing the (probably unmodified) list of input element values, but omitting any for which the final statement in the block is false.

Consider:

use strict; use warnings; my @list = 1 .. 10; for my $loopVar (@list) { print $loopVar, ' '; ++$loopVar; } print "\n@list\n\n"; print join ' ', map {$_ -= 1; $_ - 1} @list; print "\n@list\n\n"; print join ' ', grep {$_ % 2} @list; print "\n@list\n\n";

Prints:

1 2 3 4 5 6 7 8 9 10 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 10 1 3 5 7 9 1 2 3 4 5 6 7 8 9 10

Perl's payment curve coincides with its learning curve.