Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

•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


Comment on •Re: Sorting into a Specific Order
Download Code
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}

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://193731]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2014-08-01 01:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (256 votes), past polls