Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

•Re: Sorting into a Specific Order

by merlyn (Sage)
on Aug 29, 2002 at 11:10 UTC ( [id://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: &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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://193731]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-04-25 16:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found