Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

how do i sort hash by key numerically

by Anonymous Monk
on Mar 07, 2001 at 13:38 UTC ( [id://62697]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: (hashes)

if i have
%hash={ 89=>3, 45=>2, 1 =>5, 40=>3}
i want the output as
1=>5, 40=>3, 45=>2, 89=>3}
how do i do it.

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: how do i sort hash by key numerically
by arhuman (Vicar) on Mar 07, 2001 at 13:51 UTC
    for $key ( sort {$a<=>$b} keys %hash) { print "($key)->($hash{$key})\n"; }
      I've set {$a<=>$b} to show you how to change the way the list should be sorted...
      You could sort on :
      key decreasing order : {$b<=>$a}
      values-> {$hash{$a}<=>$hash{$b}}
      key length -> {length{$a}<=>length{$b}}
      or whatever...
Re: how do i sort hash by key numerically
by tomhukins (Curate) on Mar 07, 2001 at 14:46 UTC

    Effective Perl Programming's sorting recipes explains in details how you might approach this problem.

Re: how do i sort hash by key numerically
by Jouke (Curate) on Mar 07, 2001 at 13:50 UTC
    This would do the trick:
    #!/usr/bin/perl -w %hash=( 89=>3, 45=>2, 1 =>5, 40=>3); foreach (sort { $a <=> $b } keys(%hash) ) { print "key: $_ value: $hash{$_}\n" }
    Jouke Visser, Perl 'Adept'
      Are you sure that this doesn't sort typographically rather than numerically. I think the {$a<=>$b} block cited by arhuman is necessary here.
      -- I knock my pate and fancy wit will come Knock as I please, there's no one at home a pontiff paraphrased
Re: how do i sort hash by key numerically
by Anonymous Monk on Dec 08, 2003 at 17:03 UTC
    Note that while second answer produces your test output, it does NOT sort the keys numerically. Show this by strengthening your test with another key=>val pair 100=>100 and see that 100 sorts before 40.

    Originally posted as a Categorized Answer.

Re: how do i sort hash by key numerically
by bose (Initiate) on Dec 03, 2014 at 06:18 UTC
    hello everyone, your answer is ok,but i want to sort the above array by values.here '3' is two times then how?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (8)
As of 2024-04-25 11:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found