typestar

map and grep in Perl

Transform and filter lists in one line each — then chain the two into a pipeline.

use strict;
use warnings;

my @nums = (3, 1, 4, 1, 5, 9, 2, 6);

my @squares = map { $_ * $_ } @nums;
my @evens = grep { $_ % 2 == 0 } @nums;
print "@squares\n";
print "@evens\n";

# read right to left: keep the evens, then double them
my @doubled = map { $_ * 2 } grep { $_ % 2 == 0 } @nums;
print "@doubled\n";

How it works

  1. map runs its block once per element with $_ set, collecting a squared copy of the list.
  2. grep keeps only the elements whose block returns true — here the evens.
  3. Chained, the calls read right to left: grep selects the evens, then map doubles what survived.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
312
Tokens
92
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 79 seconds.

Type this snippet

Step 2 of 3 in Lists & context, step 11 of 27 in Language basics.

← Previous Next →