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's positive, it means that $b should come before $a. If it's 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 =
    (sort
        {
            if ($a < $b)
            {
                return -1;
            }
            elsif ($a > $b)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        @array
    );

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

Written by Shlomi Fish