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

I need to put hash key and value in order without using Tie::Ixhash

#!/usr/bin/perl %coins = ( "Quarter" , 25, "Dime" , 10, "Nickel", 5 ); while (($key, $value) = each(%coins)){ print $key.", ".$value."\n"; }
output shown below need to put in order, please let me know how to do + that without using Tie::Ixhash Nickel, 5 Dime, 10 Quarter, 25

Replies are listed 'Best First'.
Re: how to put hash key and value in order
by frozenwithjoy (Priest) on Dec 20, 2012 at 03:01 UTC

    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.

Re: how to put hash key and value in order
by Athanasius (Archbishop) on Dec 20, 2012 at 02:56 UTC
      Have to say, this solution

            my @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;

      is better than mine, cause it tolerates duplicated values! :)

      Cheers Rolf

Re: how to put hash key and value in order
by LanX (Saint) on Dec 20, 2012 at 02:52 UTC
    supposing that coin values are unique:
    DB<106> %coins = ( "Quarter" , 25, "Dime" , 10, "Nickel", 5 ); => ("Quarter", 25, "Dime", 10, "Nickel", 5) DB<107> %cents= reverse %coins => (25, "Quarter", 10, "Dime", 5, "Nickel") DB<108> for $cent (sort {$a<=>$b} keys %cents) { print "$cents{$cent},$cent\n" } Nickel,5 Dime,10 Quarter,25

    Cheers Rolf

Re: how to put hash key and value in order
by starX (Chaplain) on Dec 20, 2012 at 02:57 UTC
    You mean something like this?
    %coins = ( "Quarter", 25, "Dime", 10, "Nickel", 5 ); foreach my $key (sort keys %coins) { print "$key: $coins{$key}<br />"; }

      Yours will sort on keys, but I'm pretty sure the OP wants his hash sorted on values.

        Hence it was phrased in the form of a question: I wasn't sure.
Re: how to put hash key and value in order
by BradV (Sexton) on Dec 20, 2012 at 12:45 UTC