Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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

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

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

Warning: I'm the person who asked the question!

How I'd do it is
my %hash = ( foo => 2, bar => 1, baz => 3, bun => 2, ); my @array = sort {$hash{$a} <=> $hash{$b}} keys %hash;
Of course, this array only has the hash keys in it, albeit correctly sorted. If you want a data structure with both keys *and* values from %hash then you have to choose a data structure that meets your needs. A straight hash is no good, because you have duplicate values, so you'll lose some key / value pairs when you reverse them. An array of hashes is one choice:
my @array_of_hashes; push @array_of_hashes, {key => $_, value => $hash{$_}} for @sorted;
And to see what that looks like,
use Data::Dumper; print Dumper(\@array_of_hashes);
Gets you
$VAR1 = [ { 'value' => 1, 'key' => 'bar' }, { 'value' => 2, 'key' => 'bun' }, { 'value' => 2, 'key' => 'foo' }, { 'value' => 3, 'key' => 'baz' } ];
... but I'm interested to see what other monks come up with: it was my slight unease with this solution that prompted me to post this question.

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

What's my password?
Create A New User
Chatterbox?
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: (7)
As of 2014-08-22 04:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (146 votes), past polls