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
mapruns its block once per element with$_set, collecting a squared copy of the list.grepkeeps only the elements whose block returns true — here the evens.- Chained, the calls read right to left:
grepselects the evens, thenmapdoubles what survived.
Keywords and builtins used here
grepmapmyprintuse
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.
Step 2 of 3 in Lists & context, step 11 of 27 in Language basics.