Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello, How do I sort on two properties, for example I wish to sort on both id and name. If the Id is equal, then I want to check the name. So, I should get the following -

ID = 0, Name = "Barry"
ID = 1, Name = "Ian"
ID = 1, Name = "Jane"
ID = 2, Name = "Clare"

At the moment I'm doing it just for id, as follows -
@{$self->{queue}} = sort{$a->id cmp $b->id} @{$self->{queue}};

Replies are listed 'Best First'.
Re: Sort on two properties
by kyle (Abbot) on Mar 17, 2009 at 16:35 UTC

    Use cmp for comparing strings and <=> for comparing numbers (see perlop). What you want is something like this:

    @{$self->{queue}} = sort{ $a->id <=> $b->id || $a->name cmp $b->name } @{$self->{queue}};