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

I was on the FAQ here and tried to sort this hash on it's value. The value is a number and this keeps erroring out. I guess it would also be nice to sort alphabetically on the KEY if the values are the same, if that isn't too much harder.
foreach (sort $hash{$a} cmp $hash{$b} keys %hash)

Replies are listed 'Best First'.
Re: sort hash by value
by sulfericacid (Deacon) on Mar 20, 2006 at 01:00 UTC
    Hi Anonyous Monk.

    You almost had it. You need to wrap the sort in {} and the hash in parenthsis.

    foreach (sort {$hash{$a} cmp $hash{$b}} (keys %hash)

    "Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

Re: sort hash by value
by davidrw (Prior) on Mar 20, 2006 at 01:23 UTC
    sulfericacid noted the braces .. To answer your other question (secondary sort), just add an "or" clause in there:
    foreach ( sort { $hash{$a} cmp $hash{$b} || $a cmp $b } keys %hash ) +{
    Update: fixed missing paren typo as pointed out by QM
    Update: note that parens or or aren't necessary -- cmp is higher precdence (see perlop than ||
      The Perlmonks collective seems to be having a few problems today. Left off the closing paren:
      foreach (sort { $hash{$a} <=> $hash{$b} || $a cmp +$b } (keys %hash) )
      Or, alternatively, there's an extra one before "keys". ( keys %hash doesn't need parens for sort -- the parens are only needed for foreach.)

      And I avoid the use of || in these cases, because of precedence worries. Use or, and parens if needed, and eliminate one more worry.

      Update: Changed value comparison to numeric, per greywolf.

      Quantum Mechanics: The dreams stuff is made of

        The OP alludes to the fact that the hash values are numbers while the keys are strings. He will want to use '<=>' rather than 'cmp' to sort the number values properly.

        mr greywolf