map and grep
map and grep are two of Perl's most useful functions. Both take a block of code and a list, and both return a new list:
grep { CONDITION } LISTkeeps the elements for which the condition is true (filtering).map { EXPRESSION } LISTtransforms each element into zero or more new elements.
Inside the block, the current element is available as $_, Perl's "default variable".
grep: filtering a list
use strict;
use warnings;
my @temps = (12, 25, 31, 8, 19, 34);
my @hot = grep { $_ > 24 } @temps;
my @even = grep { $_ % 2 == 0 } @temps;
my $n_cold = grep { $_ < 10 } @temps; # scalar context: a count
print "Hot days: @hot\n";
print "Even values: @even\n";
print "Cold days: $n_cold\n";Hot days: 25 31 34
Even values: 12 8 34
Cold days: 1
Assigned to a scalar, grep returns the number of matches instead of the list. That makes if (grep { $_ eq $x } @list) a simple membership test.
grep also accepts a regular expression directly, which is very common when filtering text:
use strict;
use warnings;
my @files = qw(report.txt photo.jpg notes.txt logo.png data.csv);
my @text_files = grep { /\.txt$/ } @files;
my @images = grep { /\.(jpg|png)$/ } @files;
print "Text: @text_files\n";
print "Images: @images\n";Text: report.txt notes.txt
Images: photo.jpg logo.png
/\.txt$/ matches names ending in .txt. Regular expressions get several lessons of their own later.
map: transforming a list
use strict;
use warnings;
my @prices = (10, 25, 4);
my @with_tax = map { $_ * 1.2 } @prices;
my @labels = map { "\$_" } @prices;
my @upper = map { uc } qw(red green blue);
print "With tax: @with_tax\n";
print "Labels: @labels\n";
print "Upper: @upper\n";With tax: 12 30 4.8
Labels: $10 $25 $4
Upper: RED GREEN BLUE
Many built-ins like uc, lc and length use $_ when you give them no argument, so map { uc } LIST upper-cases every element.
map can return more or fewer elements
The block may return a list. Returning two values per element is the classic way to build a hash; returning an empty list () drops the element:
use strict;
use warnings;
my @words = qw(perl ruby go);
my %length_of = map { $_ => length $_ } @words;
foreach my $w (sort keys %length_of) {
print "$w has $length_of{$w} letters\n";
}
my @doubled = map { ($_, $_) } (1, 2, 3);
my @only_odd_squares = map { $_ % 2 ? $_ ** 2 : () } (1 .. 6);
print "Doubled: @doubled\n";
print "Odd squares: @only_odd_squares\n";go has 2 letters
perl has 4 letters
ruby has 4 letters
Doubled: 1 1 2 2 3 3
Odd squares: 1 9 25
Note: Hash keys come back in an unpredictable order, so the example uses
sort keysto print them alphabetically. You will see this pattern everywhere.
Chaining
Because each returns a list, map, grep and sort chain nicely. Read the chain from right to left:
use strict;
use warnings;
my @orders = (120, 45, 300, 80, 15, 210);
my @big_in_euros = map { sprintf "EUR %.2f", $_ * 0.9 }
sort { $b <=> $a }
grep { $_ >= 100 } @orders;
print "$_\n" for @big_in_euros;EUR 270.00
EUR 189.00
EUR 108.00
First grep keeps orders of at least 100, then sort orders them from largest to smallest, then map formats them.
A warning about $_
$_ inside map and grep is an alias to the original element, not a copy. Modifying $_ changes the source array:
use strict;
use warnings;
my @names = qw(ann bob);
my @caps = map { $_ = ucfirst $_; $_ } @names; # don't do this!
print "names: @names\n";
my @safe = qw(ann bob);
my @caps2 = map { ucfirst } @safe; # returns new values only
print "safe: @safe -> @caps2\n";names: Ann Bob
safe: ann bob -> Ann Bob
Keep map and grep blocks free of side effects; use a foreach loop when you really want to change an array in place.
Test yourself
What does grep { $_ > 2 } (1, 2, 3, 4) return in list context?
(1, 2)(3, 4)2(0, 0, 1, 1)
What is my $n = grep { /a/ } qw(cat dog bat);?
(cat, bat)- 2
- 1
cat
How can a map block drop an element from the result?
- Return
undef - Return the empty list
() - Call
next - Return 0