Perl Medium · Lesson 1 · On the house

map, grep, sort

List transforms; block forms; sort {$a<=>$b}. Lesson 1 is free — on the house.

Lessons · Perl Medium · Lesson 1 of 10 · On the house

map, grep, sort

List transforms; block forms; sort {$a<=>$b}.

Illustration for Perl
Lesson 1 is on the house.

map transforms a list into another list. Block form: my @doubled = map { $_ * 2 } @nums; — each $_ is an element; the block's last expression is the new value. Expression form map EXPR, LIST also works: map $_ * 2, @nums.

grep filters: my @odds = grep { $_ % 2 } @nums; keeps elements where the block is true. Like map, expression form exists: grep /a/, @words.

sort orders a list. Default is string cmp. Numeric sort needs a comparator: sort { $a <=> $b } @nums. $a and $b are the pair being compared; <=> is the numeric spaceship, cmp is stringy.

Chain them: my @top = sort { $b <=> $a } grep { $_ > 0 } map { $_ + 1 } @raw;. Each returns a list, so the next tool consumes it. Prefer block forms when the body is more than a tiny expression.

Misses: mutating $_ inside map when you meant a pure transform (it aliases the original under some uses), writing sort @nums and expecting numeric order, or treating grep as a regex-only tool (the block can be any boolean).

map-grep-sort

#!/usr/bin/env perl
use strict;
use warnings;

my @nums = (3, 1, 4, 1, 5);
my @doubled = map { $_ * 2 } @nums;
my @odds = grep { $_ % 2 } @nums;
my @asc = sort { $a <=> $b } @nums;
my @desc = sort { $b <=> $a } @nums;

print "doubled=@doubled\n";
print "odds=@odds\n";
print "asc=@asc\n";
print "desc=@desc\n";
Match this when you type.

Quiz

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

Quiz

What does grep { $_ % 2 } @nums keep?

Quiz

How do you numeric-sort ascending?

Quiz

What are $a and $b inside a sort block?

Check

Match the still for: map, grep, sort.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.