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

Could you please tell me if there is a way to sort a hash by the vaules in the hash?
Say:
%x = ("apple","232","orange","82","pear","0","banana","314");

Is there a way to sort %x by the numeral vaules, and print them out like this:
banana 314 apple 232 orange 82 pear 0

< HOW?
Thank you very much.

Replies are listed 'Best First'.
Re: How to sort a hash by its values?
by MZSanford (Curate) on Jul 19, 2001 at 20:38 UTC
    The most solid answers can be found here.
    remeber the immortal word's of Socrates who said, "I drank what ?"
Re: How to sort a hash by its values?
by Masem (Monsignor) on Jul 19, 2001 at 20:39 UTC
    Sure, you just want to sort the keys based on their values:
    my %hash = ( ... ); my @sorted_keys = sort { $hash{ $a } <=> $hash{ $b } } keys %hash; print $_, " ", $hash{ $_ }, "\n" foreach ( @sorted_keys );

    Update fixed terminology

    ----------------------------------------------------- Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
Re: How to sort a hash by its values?
by Hofmator (Curate) on Jul 19, 2001 at 20:42 UTC

    Yes, there is, have a look at

    • keys (to get the keys from the hash and then you also get the values),
    • sort (for, well, sorting),
    • perlop (for comparing numerical values) and
    • printf (for outputting nicely)
    Then write some code. And if you have any problems then come back to us.

    -- Hofmator

Re: How to sort a hash by its values?
by OzzyOsbourne (Chaplain) on Jul 20, 2001 at 15:55 UTC
Re: How to sort a hash by its values?
by earthboundmisfit (Chaplain) on Jul 19, 2001 at 20:40 UTC
    why doesn't this work?
    print $_ , "\n" foreach (sort values %x);
    Update: My poor wording made this sound like a golf. I'm really confused as to why this doesn't work but take out sort and it appears to
      That particular code won't work because without explicitly comparing the values like '$a <=> $b', the sort function will treat the values as strings and sort based on the first byte rather than its integer value.

      So rather than:

      314 232 82 0
      You get:
      0 232 314 82

      Hope that helps.

      Amel - f.k.a. - kel