grep and map

grep

grep keeps the elements for which the block returns true. The block sees each element in $_, and the result is a new list in the original order.

my @nums = (3, 8, 1, 12); my @big = grep { $_ > 5 } @nums; print "@big\n"; # 8 12

perl demo.pl

8 12

A pattern goes straight in the block, which makes grep the natural filter for lines. The comma after the block is optional but reads well when the block is long.

my @lines = ("ok: db", "fail: db", "ok: web"); my @bad = grep { /^fail/ } @lines; print "@bad\n"; # fail: db

perl demo.pl

fail: db

map

map transforms every element and returns the list of results. The block is evaluated in list context, so one element may produce zero, one or several outputs.

my @nums = (3, 8, 1, 12); my @squares = map { $_ * $_ } @nums; print "@squares\n"; # 9 64 1 144 my @upper = map { uc } qw(perl ruby); print "@upper\n"; # PERL RUBY

perl demo.pl

9 64 1 144
PERL RUBY

A map in void context is a warning sign: the block ran, the results were thrown away, and only side effects remain. Use a for loop when that is really what you want.

Chain them

Both take a list and return a list, so they compose. Read the chain from the bottom up: rename the files, keep the logs, sort the result.

my @files = qw(app.log db.log notes.txt); my @report = sort map { uc } grep { /\.log$/ } @files; print "@report\n"; # APP.LOG DB.LOG

perl demo.pl

APP.LOG DB.LOG

Count and first

In scalar context grep returns a count, so counting matches needs no loop. For the first match, List::Util ships with Perl and stops as soon as it finds one, unlike grep on a huge list.

use List::Util qw(first); my @nums = (3, 8, 1, 12); my $n = grep { $_ > 5 } @nums; print "$n big\n"; # 2 big my $hit = first { $_ > 5 } @nums; print "first: $hit\n"; # first: 8

perl demo.pl

2 big
first: 8

List::Util also offers sum, max, min, any, all and none. Reach for them before writing a loop that reimplements one of those names.

Next: Sort and the Schwartzian transform

Article author: Arthur Isaev