Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^2: sort hash by value

by QM (Parson)
on Mar 20, 2006 at 01:30 UTC ( [id://537852]=note: print w/replies, xml ) Need Help??


in reply to Re: sort hash by value
in thread sort hash by value

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

Replies are listed 'Best First'.
Re^3: sort hash by value
by greywolf (Priest) on Mar 20, 2006 at 21:09 UTC
    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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://537852]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-25 07:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found