http://www.perlmonks.org?node_id=193731


in reply to Sorting into a Specific Order

Since your example was sketchy, I'll have to give you only an example:
my @aoh = ( { first => 'fred', last => 'flintstone', age => 30 }, { first => 'wilma', last => 'flintstone', age => 26 }, { first => 'pebbles', last => 'flintstone', age => 3 }, { first => 'barney', last => 'rubble', age => 28 }, { first => 'betty', last => 'rubble', age => 24 }, { first => 'bammbamm', last => 'rubble', age => 2 }, { first => 'mr.', last => 'slate', age => 35 }, ); # The boss comes first! my %lastname_sortorder = qw( flintstone 2 rubble 3 slate 1 ); my @sorted = sort { $lastname_sortorder{$a->{last}} <=> $lastname_sortorder{$b->{last}} +or # primary is lastname sort order $a->{age} <=> $b->{age} # secondary is age } @aoh;
The key here is to create an "ordering table" which is used for the comparison, then look up your non-linear sort key in this ordering table, and sort on that instead.

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: &bull;Re: Sorting into a Specific Order
by Notromda (Pilgrim) on Aug 29, 2002 at 15:10 UTC
    ++merlyn for showing me a new trick - I didn't know you could put an "or" in the sort routine to get a secondary sort. thanks!
      You should get a copy of the llama then. That "trick" is in there, along with some other stuff you likely don't know then. {grin}

      -- Randal L. Schwartz, Perl hacker


      update: I just noticed that this is my 3000th post. Nice that it also happened to be about the llama. {grin}