"Perl for Perl Newbies" - Part 2Useful Functionssort

9.3. sort

The sortfunction can sort an array based on a comparison expression. As with the mapfunction, 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 $aand $bindicate the two elements to be compared. If the expression returns a negative value it means that $ashould precede $b. If it is positive, it means that $bshould 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 =
    (
sort
        {

if (
$a <
$b)
            {

return -
1;
            }

elsif (
$a >
$b)
            {

return
1;
            }

else
            {

return
0;
            }
        }

@array
    );

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

Written by Shlomi Fish