PERL / CHAPTER 09

Filtering, mapping, and numeric order

Advanced

Build predictable transformations with the right comparison and without accidental mutation.

By the end of this chapter

  • Use grep to retain elements
  • Use map to transform values
  • Choose numeric sort comparison

The idea

Enter with list context and blocks understood. grep retains values for which its block is true, while map produces transformed values. Both commonly use $_ for the current item. Treat that item as read-only unless modifying the source is intentional, because these operations can expose aliases. A pipeline should make it clear which stage selects data and which stage changes its representation.

sort without a comparison block uses string ordering, which may place ten before two. Use the numeric spaceship comparison $a <=> $b when ordering numeric values. The special sort variables $a and $b supply the compared pair. A comparator must consistently describe the requested order; do not use a boolean equality expression as if it were a three-way comparison. The example sorts an independent result list for display.

Perl example
use strict; use warnings;
my @values=(10,3,2,7);
my @result=sort {$a <=> $b} map {$_ * 2} grep {$_ >= 3} @values;
print join(",",@result),"\n";
Result
6,14,20

Filtering keeps ten, three, and seven. Doubling gives twenty, six, and fourteen, then numeric sorting orders them ascending.

Try it yourself

Sort a list of integer scores descending without changing the original array.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which comparison block sorts numbers ascending?