"Perl for Perl Newbies" - Part 4More about || and &&For sort()

5.1. For sort()

The || operator can be used in sort, in conjunction with operators such as cmp or <=> to sort according to several criteria. For example, if you wish to sort according to the last name and if this is equal according to the first name as well, you can write the following:

#!/usr/bin/perl

use strict;
use warnings;


my @array =
(
    { 'first' => "Amanda", 'last' => "Smith", },
    { 'first' => "Jane", 'last' => "Arden",},
    { 'first' => "Tony", 'last' => "Hoffer", },
    { 'first' => "Shlomi", 'last' => "Fish", },
    { 'first' => "Chip", 'last' => "Fish", },
    { 'first' => "John", 'last' => "Smith", },
    { 'first' => "Peter", 'last' => "Torry", },
    { 'first' => "Michael", 'last' => "Hoffer", },
    { 'first' => "Ben", 'last' => "Smith", },
);

my @sorted_array =
    (sort
        {
            ($a->{'last'} cmp $b->{'last'}) ||
            ($a->{'first'} cmp $b->{'first'})
        }
        @array
    );

foreach my $record (@sorted_array)
{
    print $record->{'last'} . ", " . $record->{'first'} . "\n";
}

Its output is:

Arden, Jane
Fish, Chip
Fish, Shlomi
Hoffer, Michael
Hoffer, Tony
Smith, Amanda
Smith, Ben
Smith, John
Torry, Peter

Written by Shlomi Fish