Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between grep and map in Perl?

Tags:

grep

map

perl

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 between the two?

like image 211
Nathan Fellman Avatar asked Feb 22 '09 19:02

Nathan Fellman


3 Answers

grep returns those elements of the original list that match the expression, while map returns the result of the expression applied to each element of the original list.

$ perl -le 'print join " ", grep $_ & 1, (1, 2, 3, 4, 5)'
1 3 5
$ perl -le 'print join " ", map $_ & 1, (1, 2, 3, 4, 5)'
1 0 1 0 1

The first example prints all the odd elements of the list, while the second example prints a 0 or 1 depending on whether the corresponding element is odd or not.

like image 115
Greg Hewgill Avatar answered Oct 23 '22 01:10

Greg Hewgill


I find that it's helpful to think think about grep() and map() in their most general form:

grep {BLOCK} LIST   
map  {BLOCK} LIST

grep() is a filter: it returns the subset of items from LIST for which BLOCK returns true.

map() is a mapping function: send a value from LIST into BLOCK, and BLOCK returns a list of 0 or more values; the combined set of all of those calls to BLOCK will be the ultimate list returned by map().

like image 10
FMc Avatar answered Oct 23 '22 03:10

FMc


map applies a function to all elements in a list and returns the result.

grep returns all elements in a list that evaluate to true when a function is applied to them.

my %fruits = (
  banana => {
    color => 'yellow',
    price => 0.79,
    grams => 200
  },
  cherry => {
    color => 'red',
    price => 0.02,
    grams => 10
  },
  orange => {
    color => 'orange',
    price => 1.00,
    grams => 225
  }
);

my %red_fruits = map { $_ => $fruits{$_} }
                   grep { $fruits{$_}->{color} eq 'red' }
                     keys(%fruits);

my @prices = map { $fruits{$_}->{price} } keys(%fruits);
my @colors = map { $fruits{$_}->{color} } keys(%fruits);
my @grams  = map { $fruits{$_}->{grams} } keys(%fruits);

# Print each fruit's name sorted by price lowest to highest:
foreach( sort { $fruits{$a}->{price} <=> $fruits{$b}->{price}} keys(%fruits) )
{
  print "$_ costs $fruits{$_}->{price} each\n";
}# end foreach()
like image 4
JDrago Avatar answered Oct 23 '22 03:10

JDrago