Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: sorting arrays in respect to a different hash's values

by linuxer (Curate)
on May 23, 2009 at 14:19 UTC ( [id://765827]=note: print w/replies, xml ) Need Help??


in reply to sorting arrays in respect to a different hash's values

Maybe this little example helps.

#!/usr/bin/perl -l use strict; use warnings; my %hash = ( foo => 1, whatever => { rank => 11 }, you => { rank => 2 }, want => { rank => 7 }, ); my @arr = grep { $_ ne 'foo' } keys %hash; my @sorted = sort { $hash{$a}->{rank} <=> $hash{$b}->{rank} } @arr; print "@arr"; print "@sorted";

Update:

modified test data in code

If your hash values are plain strings, than you just need to do something like:

my @sorted = sort { $hash{$a} cmp $hash{$b} } @arr;

See sort for more information about sort and the ways, how you can influence the sort.

Also see Schwartzian Transform

Update2: replaced <=> with cmp in second example; Thanks to AnomalousMonk and roboticus for pointing me on that.

Log In?
Username:
Password:

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

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

    No recent polls found