Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

•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]
[Tux]: C99 is not supported on HP-UX before 11.31
[Tux]: at least not reliable. And perl itself requires C89 (but probes if it can safely use some C99 features)
Eily takes a peek in the last hour of CB to discover that LanX woke up is boobs with some Queen :P
[Eily]: s/\K\bis\b/h/
[Tux]: you left the space in
[Tux]: and that \K is not required
[Tanktalus]: 11.31 is already 10 years old... you still need to support versions older than that? My condolences :)
[Eily]: meh, got confused. s/(?=\bis\b)/h/ will work better :)

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (11)
As of 2017-09-20 16:36 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (237 votes). Check out past polls.