in reply to Sorting Keys and Values

Here is one way to do it: make a hash of arrays of users who have the same score. Sort the keys, print, ta ta.
#!/usr/bin/perl -w %db = ( 'scores' => { 'user1' => 200, 'user2' => 190, 'user3' => 232, 'user4' => 187, 'user5' => 190 } ); my %scores; while (my ($u,$s) = each %{$db{'scores'}}){ push @{$scores{$s}}, $u; } my $i = 1; for(sort {$b <=> $a} keys %scores){ local $"=", "; print "$i Place: ($_ Points) @{$scores{$_}}\n"; $i++; } __END__ 1 Place: (232 Points) user3 2 Place: (200 Points) user1 3 Place: (190 Points) user2, user5 4 Place: (187 Points) user4
PS: output slightly different

Replies are listed 'Best First'.
Re: Re: Sorting Keys and Values
by Kanji (Parson) on Apr 27, 2002 at 13:57 UTC

    Taking a lead from Corion, if you did want sports rankings (and without additional modules), just change $i++ to ...

    $i += @{$scores{$_}};

    ... which will automatically make the next available rank skip N ranks if you have tied users. (ie, 1st, 2nd, 3rd, 5th assuming two people ranked 3rd.)

        --k.


Re: Re: Sorting Keys and Values
by mt2k (Hermit) on Apr 27, 2002 at 09:33 UTC
    Thank you so much abstract! Thank you too vladb! I am using abstracts' code for a couple reasons: 1. Short 2. No excess commas 3. Just looks nicer in all :)