Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Answer: How do I sort a hash by its values?

( #138361=categorized answer: print w/ replies, xml ) Need Help??

Q&A > hashes > How do I sort a hash by its values? contributed by tye

Don't make another structure. Just keep both the array and the hash handy. If you want all of the values (sorted), you simply do:     my @values= @hash[@array];
So, if you want the 3rd key and value, you use:
my $key= @array[2]; my $value= $hash{$key};
instead of, using your data structure:
my $key= $array_of_hashes[2]{key}; my $value= $array_of_hashes[2]{value};
or     my( $key, $value )= @{$array_of_hashes[2]}{qw( key value )};
The original array and hash also store the data using quite a bit less memory.

Comment on Answer: How do I sort a hash by its values?
Select or Download Code
Log In?

What's my password?
Create A New User
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2015-11-28 22:31 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (746 votes), past polls