This works for me:
use strict; my %db = ( 'scores' => { 'user1' => 200, 'user2' => 190, 'user3' => 232, 'user4' => 187, 'user5' => 190 } ); my %sorted_scores; # # Generate another hash structure where # scores are used for keys and values # hold list of users who got that score. # # hash is a wonderful thing ;-) # for (keys %{$db{'scores'}}) { push @{$sorted_scores{$db{'scores'}{$_}}}, $_; } my $i = 1; for my $score (sort {$b <=> $a} keys %sorted_scores) { print "$i Place: "; for (@{$sorted_scores{$score}}) { print "$_ ($score), "; } print "\n"; $i++; }
This code produces the following output:
1 Place: user3 (232), 2 Place: user1 (200), 3 Place: user2 (190), user5 (190), 4 Place: user4 (187),
The only remaining part is to remove excessive commas and also print numbers in a slightly different format... (adding 'st' to 1 and 'nd' to 2 etc.)

Cheers, vladb.

"There is no system but GNU, and Linux is one of its kernels." -- Confession of Faith

In reply to Re: Sorting Keys and Values by vladb
in thread Sorting Keys and Values by mt2k

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.