Lhamo_rin has asked for the wisdom of the Perl Monks concerning the following question:

Monks,

This seems to be a simple question but one I have not found an answer for in the monastery.

I want to sort a hash from highest to lowest value.

For example:

%hash = ( 5.764 => a, 3.24 => b, 4.6 => c);

I would want this to print out as:

5.764 a

4.6 c

3.24 b

Thanks,

Replies are listed 'Best First'.
Re: sorting a hash
by Samy_rio (Vicar) on Feb 28, 2006 at 12:51 UTC

    Hi, Try this,

    use strict; use warnings; my %hash = ( 5.764 => 'a', 3.24 => 'b', 4.6 => 'c'); print "$_\t$hash{$_}\n" for reverse sort keys %hash; __END__ 5.764 a 4.6 c 3.24 b

    You should view How (Not) To Ask A Question.

    Regards,
    Velusamy R.


    eval"print uc\"\\c$_\""for split'','j)@,/6%@0%2,`e@3!-9v2)/@|6%,53!-9@2~j';

      The OP doesn't state this clearly, but I assume that he means numerically sorted, rather than lexically.

      print "$_\t$hash{$_}\n" for reverse sort { $a <=> $b } keys %hash; # or simply print "$_\t$hash{$_}\n" for sort { $b <=> $a } keys %hash;
Re: sorting a hash
by mickeyn (Priest) on Feb 28, 2006 at 12:52 UTC
    From your expected output you probably meant sorting the keys and not the values of the hash.

    foreach ( sort {$b <=> $a} keys %hash ){ print $_," ",$hash{$_},"\n"; }
    should answer your question (decending numeric key sorting).

    Enjoy,
    Mickey

Re: sorting a hash
by Fletch (Bishop) on Feb 28, 2006 at 13:45 UTC

    See also perldoc -q sort.

Re: sorting a hash
by ashokpj (Hermit) on Feb 28, 2006 at 14:50 UTC
    use strict; use warnings; my %hash = ( 23=> "er",3.5 =>"rt", 56=>"ssd",7=>"ert"); print "$_:-:$hash{$_}\n" for sort {$b <=> $a} keys %hash;

    To learn more about sorting go through following site

      http://www.perlfect.com/articles/sorting.shtml
Re: sorting a hash
by Jasper (Chaplain) on Feb 28, 2006 at 14:29 UTC
    Funny, I typed 'sort hash' into the text box in the top left hand corner of this page, and got a load of relevant results. Perhaps the search facility was broken when you tried to find an answer for this.