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

Helo monks, How do I sort this HoH based on the 'score'?
my $HoH = { 'pk1' => { 'sk1' => 'val1', 'sk2' => 'val2, 'score'=> 47 }, 'pk2' => { 'sk1' => 'val3', 'sk2' => 'val4', 'score' => 14 }, 'pk3' => { 'sk1' => 'val5', 'sk2' => 'val6', 'score' => 64 } };
I have this snippet that try to get the sorted keys.
my @best_key = sort { keys %{$HoH{'score'}{$a}} <=> keys %{$HoH{'score +'}{$b}} } keys %HoH;
Supposedly it returns: pk3,pk1,pk2 as result. But it fails. Many thanks for your time.

Replies are listed 'Best First'.
Re: Sorting HoH
by Hena (Friar) on May 25, 2005 at 07:29 UTC
    This kind of questions tend to have answers in Q&A. I would suggest reading node 320255.
Re: Sorting HoH
by holli (Abbot) on May 25, 2005 at 07:33 UTC
    You cannot sort a hash. All you can get is a list of sorted keys:
    my $HoH = { 'pk1' => { 'sk1' => 'val1', 'sk2' => 'val2', 'score' => 47, }, 'pk2' => { 'sk1' => 'val3', 'sk2' => 'val4', 'score' => 14 }, 'pk3' => { 'sk1' => 'val5', 'sk2' => 'val6', 'score' => 64 } }; my @keys = sort { $HoH->{$a}->{score} <=> $HoH->{$b}->{score} } keys % +{$HoH}; print "@keys";


    holli, /regexed monk/
      You cannot sort a hash

      I dunno...  sort %hash seems to work for me :)
Re: Sorting HoH
by Fang (Pilgrim) on May 25, 2005 at 07:34 UTC

    my @best_keys = sort { $HoH->{$a}{'score'} <=> $HoH->{$b}{'score'} } keys %{$HoH}

    The $a and $b special variables are taken from keys %{$HoH}, so that's where they should be in the sort sub. Reread perldoc -f sort.

    Note you're missing a closing ' in your code, too ('sk2' => 'val2,).

    Update: just noticed you wanted the keys in descending order of their score value, just swap $a and $b in the code.

Re: Sorting HoH
by thcsoft (Monk) on May 25, 2005 at 08:48 UTC
    perldoc perldata perldoc -f sort


    language is a virus from outer space.