Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: how to put hash key and value in order

by frozenwithjoy (Curate)
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.


Comment on Re: how to put hash key and value in order
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1009677]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (8)
As of 2014-09-22 06:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (182 votes), past polls