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

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

by linuxer (Curate)
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";


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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://765827]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2018-06-23 20:12 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (125 votes). Check out past polls.