Ad space (banner)
Lesson 18 / 20

Sorting (sort)

This lesson covers the sort function, which reorders an array.

By default sort orders values as strings, alphabetically. To sort numbers correctly you specify the comparison, as in sort { $a <=> $b } @array.

The sample code sorts my @nums = (30, 5, 100, 1); into numeric order with sort { $a <=> $b } @nums;.

A common early stumble is writing plain sort @nums and getting string order rather than numeric order. That easily produces surprises such as "100" coming before "30".

In professional work, sorting is an everyday operation — putting aggregated results into ranking order, for example.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Perl directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)