"Perl for Perl Newbies" - Part 2Useful Functionssort<=> and cmp

9.3.1. <=> and cmp

Perl has two operators <=> and cmp, which are very useful when wishing to sort arrays. $x <=> $y returns -1 if $x is numerically lesser than $y, 1 if it's greater, and zero if they are equal.

cmp does the same for string comparison. For instance the previous example could be re-written as:

use strict;
use warnings;

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

my @sorted_array = (sort { $a <=> $b } @array);

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

Much more civil, isn't it? The following example, sorts an array of strings in reverse:

use strict;
use warnings;

my @input = (
    "Hello World!",
    "You is all I need.",
    "To be or not to be",
    "There's more than one way to do it.",
    "Absolutely Fabulous",
    "Ci vis pacem, para belum",
    "Give me liberty or give me death.",
    "Linux - Because software problems should not cost money",
);

# Do a case-insensitive sort
my @sorted = (sort { lc($b) cmp lc($a); } @input);

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

Written by Shlomi Fish