Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: sort hash by value

by davidrw (Prior)
on Mar 20, 2006 at 01:23 UTC ( [id://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.

    -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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://537851]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2024-04-19 11:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found