Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

•Re: Sorting into a Specific Order

by merlyn (Sage)
on Aug 29, 2002 at 11:10 UTC ( #193731=note: print w/replies, xml ) Need Help??

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: •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}

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://193731]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (6)
As of 2017-08-17 14:55 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (288 votes). Check out past polls.