"Perl for Perl Newbies" - Part 2Useful Functionssort

9.3. sort

The sort function can sort an array based on a comparison expression. As with the map function, this expression can be as complex as you'd like and may actually include a call to a dedicated function.

Within the comparison block, the variables $a and $b indicate the two elements to be compared. If the expression returns a negative value it means that $a should precede $b. If it is positive, it means that $b should come before $a. If it is zero, it indicates that it does not matter which one will come first.

The following example sorts an array of integers numerically:

use strict;
use warnings;

my @array = (100,5,8,92,-7,34,29,58,8,10,24);

my @sorted_array =
            if ($a < $b)
                return -1;
            elsif ($a > $b)
                return 1;
                return 0;

print join(",", @sorted_array), "\n";

Written by Shlomi Fish