Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: sort hash by value

by davidrw (Prior)
on Mar 20, 2006 at 01:23 UTC ( #537851=note: print w/replies, xml ) Need Help??

in reply to sort hash by value

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 ||

Replies are listed 'Best First'.
Re^2: sort hash by value
by QM (Parson) on Mar 20, 2006 at 01:30 UTC
    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

      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://537851]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2018-06-19 20:10 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (114 votes). Check out past polls.