You can pass a custom comparison function to Perl's sort routine. Just use:
@sorted = sort { $a <=> $b } @unsorted;
The sort
function accepts a custom comparison function as its first argument, in the form of a code block. The {...}
part is just this code block (see http://perldoc.perl.org/functions/sort.html ).
sort
will call this custom comparison function whenever it needs to compare two elements from the array to be sorted. sort
always passes in the two values to compare as $a
, $b
, and the comparison function has to return the result of the comparison. In this case it just uses the operator for numeric comparison (see http://perldoc.perl.org/perlop.html#Equality-Operators ), which was probably created just for this purpose :-).
Solution shamelessly stolen from "Perl Cookbook", Chapter 04 Sub-chapter 15 (buy the book - it's worth it!)