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.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does grep { ... } @list return?

    Answer

    A new list of the elements for which the block returned true, in the original order

    grep filters and keeps the order; in scalar context the same call returns a count instead.

  2. Which variable holds the current element inside a grep or map block?

    Answer

    $_

    The block sees each element in the default variable, which is why a bare pattern match works too.

  3. What does map { $_ * $_ } @nums return?

    Answer

    A list with the square of every element, in the same order

    map evaluates the block once per element and collects the results as a list.

  4. Why is a map in void context a warning sign?

    Answer

    The results are thrown away, so only the side effects of the block remain

    A map that is not assigned and not printed is a for loop written in the wrong shape.

  5. How do you read a chain of sort, map and grep?

    Answer

    From the bottom up: the last line is the input, and each step above transforms the result

    Each operator takes the list returned by the one below it, so the data flows upward.

  6. What does first { $_ > 5 } @nums give you that grep does not?

    Answer

    It stops at the first match instead of walking the whole list

    first from List::Util stops as soon as the block is true, which matters on a huge list.

  7. What does this program print? my @n = (1, 5, 9); my @b = grep { $_ > 4 } @n; print "@b\n";

    Answer

    5 9

    Only the elements above four survive the filter, in their original order.

  8. What does this program print? my @n = (1, 2, 3); my @s = map { $_ * 2 } @n; print "@s\n";

    Answer

    2 4 6

    The block doubles each element and the resulting list keeps the order.

  9. What does this program print? my @n = (1, 5, 9); my $c = grep { $_ > 4 } @n; print "$c\n";

    Answer

    2

    In scalar context grep returns the number of matches, which is 2 here.

  10. What does this program print? use List::Util qw(sum); my @n = (1, 2, 3); print sum(@n), "\n";

    Answer

    6

    List::Util is in the core, and sum adds the list to 6.

Article author: Arthur Isaev