AnyCompiler

List Processing with map, grep, and sort

map, grep, and sort are Perl's functional list-processing core, and idiomatic Perl leans on them constantly instead of writing out explicit loops. map { expression } @list transforms every element and returns the results as a new list. grep { condition } @list keeps only the elements for which the block is true.

use strict;
use warnings;

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

my @doubled = map { $_ * 2 } @nums;
print "Doubled: @doubled\n";

my @evens = grep { $_ % 2 == 0 } @nums;
print "Evens: @evens\n";

my @sorted = sort { $b <=> $a } @nums;
print "Descending: @sorted\n";
Output
Doubled: 2 4 6 8 10 12
Evens: 2 4 6
Descending: 6 5 4 3 2 1

sort's comparator block uses the special package variables $a and $b (not lexical my variables — Perl wires those two names up specifically for sort) and returns negative, zero, or positive the way a C-style comparator does. <=> is the numeric three-way comparison operator; cmp is its string equivalent. sort { $b <=> $a } reverses the usual ascending order by swapping $a and $b in the comparison.

All three combine naturally into a pipeline, read right to left (innermost first): sort the list, keep only the elements that pass a test, then transform what's left.

use strict;
use warnings;

my @words = ("pear", "fig", "banana", "kiwi", "apple");

my @longWordsUpper =
    map  { uc $_ }
    grep { length($_) > 4 }
    sort @words;

print "Result: @longWordsUpper\n";
Output
Result: APPLE BANANA

Next: file handling — reading input with the diamond operator, which is also how real Perl scripts read actual files.

Practice exercise

Given my @nums = (3, 8, 1, 9, 4), use grep to keep numbers greater than 3, then map to square each one, then print the results joined by spaces.