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

I have the following code:
$hash{me}{sorter_total}=10; $hash{john}{sorter_total}=30; $hash{landon}{sorter_total}=20; $hash{jimmy}{sorter_total}=40; foreach my $user ($hash) { @sorted = (sort {$b <=> $a} keys %{$hash{$user}{sorter_total}}); } foreach (@sorted) { print "$_\n"; }
I'm trying to get it to print in order according to the value of sorter_total as follows:
jimmy
john
landon
me

I realize the data structure doesn't look right when this is all you see, but I just narrowed my problem down to this bit of sample code. How to get them to print according to value?

Thank you!

Replies are listed 'Best First'.
Re: Sorting Problem
by atcroft (Abbot) on Mar 11, 2005 at 21:15 UTC

    Instead of the for loop you have just below the data, try the following:

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

    This sorts the key valus of %hash based on a comparison of the value of $hash{$key}{sorter_total}, which sounds like what you desire.

    HTH.

Re: Sorting Problem
by Anonymous Monk on Mar 11, 2005 at 21:18 UTC
    It always amazes me how I can mess with something for an hour and someone can come and solve my problem with one simple line! Thanks much.
      It always amazes me how I can mess with something for an hour and someone can come and solve my problem with one simple line!
      perldoc is your friend:
      perldoc -q "sort a hash"

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of