Tutorial by Examples

@sorted = sort @list; @sorted = sort { $a cmp $b } @list; sub compare { $a cmp $b } @sorted = sort compare @list; The three examples above do exactly the same thing. If you don't supply any comparator function or block, sort assumes you want the list on its right sorted lexically. This is ...
@sorted = sort { $a <=> $b } @list; Comparing $a and $b with the <=> operator ensures they are compared numerically and not textually as per default.
@sorted = sort { $b <=> $a } @list; @sorted = reverse sort { $a <=> $b } @list; Sorting items in descending order can simply be achieved by swapping $a and $b in the comparator block. However, some people prefer the clarity of a separate reverse even though it is slightly slower.
This is probably the most famous example of a sort optimization making use of Perl's functional programming facilities, to be used where the sort order of items depend on an expensive function. # What you would usually do @sorted = sort { slow($a) <=> slow($b) } @list; # What you do to ma...
The traditional technique to make sort ignore case is to pass strings to lc or uc for comparison: @sorted = sort { lc($a) cmp lc($b) } @list; This works on all versions of Perl 5 and is completely sufficient for English; it doesn't matter whether you use uc or lc. However, it presents a problem ...

Page 1 of 1