Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

sort hash by value

by Anonymous Monk
on Mar 20, 2006 at 00:54 UTC ( #537849=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I was on the FAQ here and tried to sort this hash on it's value. The value is a number and this keeps erroring out. I guess it would also be nice to sort alphabetically on the KEY if the values are the same, if that isn't too much harder.
foreach (sort $hash{$a} cmp $hash{$b} keys %hash)

Comment on sort hash by value
Download Code
Re: sort hash by value
by sulfericacid (Deacon) on Mar 20, 2006 at 01:00 UTC
    Hi Anonyous Monk.

    You almost had it. You need to wrap the sort in {} and the hash in parenthsis.

    foreach (sort {$hash{$a} cmp $hash{$b}} (keys %hash)


    "Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

    sulfericacid
Re: sort hash by value
by davidrw (Prior) on Mar 20, 2006 at 01:23 UTC
    sulfericacid noted the braces .. To answer your other question (secondary sort), just add an "or" clause in there:
    foreach ( sort { $hash{$a} cmp $hash{$b} || $a cmp $b } keys %hash ) +{
    Update: fixed missing paren typo as pointed out by QM
    Update: note that parens or or aren't necessary -- cmp is higher precdence (see perlop than ||
      The Perlmonks collective seems to be having a few problems today. Left off the closing paren:
      foreach (sort { $hash{$a} <=> $hash{$b} || $a cmp +$b } (keys %hash) )
      Or, alternatively, there's an extra one before "keys". ( keys %hash doesn't need parens for sort -- the parens are only needed for foreach.)

      And I avoid the use of || in these cases, because of precedence worries. Use or, and parens if needed, and eliminate one more worry.

      Update: Changed value comparison to numeric, per greywolf.

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of

        The OP alludes to the fact that the hash values are numbers while the keys are strings. He will want to use '<=>' rather than 'cmp' to sort the number values properly.


        mr greywolf

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2014-09-21 02:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (165 votes), past polls