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

Hi,
I use the following ->
foreach my $person (sort keys %values) { print $person,"\t",$values{$person},br; }
to display the number I've assigned to each person, in alphabetical order. But how do I output in numberical order? Such as ->
Steve 1000
John 977
Alice 555
Mike 555
Zoe 555

Using the hash %values?

Replies are listed 'Best First'.
Re: hashes sorted by value, but displaying both keys and values
by hardburn (Abbot) on Dec 31, 2003 at 21:37 UTC
    foreach my $person (sort { $values{$a} <=> $values{$b} } keys %values) + { . . .
Re: hashes sorted by value, but displaying both keys and values
by mpeppler (Vicar) on Dec 31, 2003 at 21:38 UTC
    foreach my $person (sort { $values{$b} <=> $values{$a} } keys(%values) +) { ... }
    Michael
Re: hashes sorted by value, but displaying both keys and values
by chromatic (Archbishop) on Dec 31, 2003 at 21:38 UTC

    How about this?

    for my $person (sort { $values{$a} <=> $values{$b} } keys %values) { print "$person\t$values{$person}", br(); }

    Update: Removed incorrect dereferencing arrows and changed sorting scheme. I'd originally done this as a Schwartzian Transform before realizing that it was unnecessary. Less post, more sleep.

      Hi thanks for that, but I also need to sort alphabetically if the same number is associated with a number of people, such as ->
      Steve 1000
      John 977
      Alice 555
      Mike 555
      Zoe 555

      I'm currently getting something like ->
      Steve 1000
      John 977
      Mike 555
      Alice 555
      Zoe 555

        No problem, just throw an extra comparison in the sort block as documented in perldoc -f sort:

        sort { $values{$a} <=> $values{$b} || $a cmp $b } keys %values