Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: how to put hash key and value in order

by frozenwithjoy (Priest)
on Dec 20, 2012 at 03:01 UTC ( #1009677=note: print w/replies, xml ) Need Help??


in reply to how to put hash key and value in order

To sort by ascending value:

say "$_: $coins{$_}" for sort { $coins{$a} <=> $coins{$b} } keys %coins;

To sort by descending value:

say "$_: $coins{$_}" for sort { $coins{$b} <=> $coins{$a} } keys %coins;

To sort by ascending value followed by descending key (not really applicable for this coin example, but good to know):

say "$_: $coins{$_}" for sort { ( $coins{$a} <=> $coins{$b} ) || ( $a cmp $b ) } keys %coins;

Note: Be sure to use <=> for numerical sorts and cmp for alphabetical.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (10)
As of 2016-12-05 13:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (82 votes). Check out past polls.