Lesson 24 of 55
10 mins readPython Functional List Processing: map, grep & sort
In Plain English
Perl offers functional list pipelines: `grep` filters elements matching a condition, `map` transforms each element, and `sort` orders elements using `$a` and `$b`.
Deep Dive: How It Works
grep { condition } @list: Returns items where the block evaluates to true ($a is tested as $_).
map { expression } @list: Evaluates expression for each $_ and returns the transformed list.
Numeric Sort: `sort { $a <=> $b } @numbers` (spaceship operator).
String Sort: `sort { $a cmp $b } @strings` (lexicographical comparison).
Core Rules to Remember

grep for Filtering: Keeps elements where `{ ... }` evaluates to true.

map for Transformation: Transforms each `$_` element into new list items.

Special $a and $b in sort: Use `<=>` for numeric sort and `cmp` for alphabetical sort.
Live Interactive Example
Hit Run Code to see it liveData Pipeline with grep, map, and sort
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Output Console
Click "Run Code" to view the rendered output.
How it works: grep selected 8, 6, 2, 4; map squared them; sort ordered them.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Filter and Double with grep & map
Declare `my @nums = (1, 5, 10, 15, 20);`
Filter numbers `> 8` with `grep`, then double them with `map`.
Print `"Doubled: " . join(" ", @doubled) . "\n"`.
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.