Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re^2: sort hash by value

by QM (Parson)
on Mar 20, 2006 at 01:30 UTC ( #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.

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?

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2018-07-20 01:47 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (422 votes). Check out past polls.