Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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

by linuxer (Deacon)
on May 23, 2009 at 14:19 UTC ( #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.


Comment on Re: sorting arrays in respect to a different hash's values
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (11)
As of 2014-10-22 16:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (119 votes), past polls