In Perl both grep
and map
take an expression and a list, and evaluate the expression for each element of the list.
What is the difference b
One other thing about grep
: in a scalar context it tells you how many items it found. This can be useful if you don't really want a second list, but you do want to know how many items of a certain kind there are.
my @numbers = qw/1 2 3 4 5 6/;
my @odd_numbers = grep { $_ & 1 } @numbers; # grep returns (1, 3, 5)
my $how_many_odd = grep { $_ & 1 } @numbers; # grep returns 3
Edit: Since the OP asked in a comment, I should say that you can use map
in a scalar context in the same way. The point wasn't that grep
is the only one of the two that can do this, but that it sometimes comes in handy to do this with grep
.