Hi, keep track of the ranking as you go through the sorted list, and only increment it if the value is lower.

Update: ++haukex posted basically the same solution while I was dithering over syntax, LOL!

use strict; use warnings; use feature 'say'; use Data::Dumper; $Data::Dumper::Sortkeys = $Data::Dumper::Terse = 1; my %data = ( car => 180, motorcycle => 150, skate => 150, bird => 120, ); my @sorted = sort { $data{$b} <=> $data{$a} } keys %data; my $rank; my %result; for ( 0 .. $#sorted ) { my $curr_key = $sorted[$_]; my $prev_key = $_ ? $sorted[$_ - 1] : undef; if ( not $prev_key ) { $rank = 1; } elsif ( $data{$curr_key} != $data{$prev_key} ) { $rank++; } else { # values are the same, leave $rank unchanged } $result{$curr_key} = { val => $data{$curr_key}, rank => $rank }; } say "$_: ", Dumper $result{$_} for @sorted; __END__
Output:
perl 1207623.pl car: { 'rank' => 1, 'val' => 180 } skate: { 'rank' => 2, 'val' => 150 } motorcycle: { 'rank' => 2, 'val' => 150 } bird: { 'rank' => 3, 'val' => 120 }

Hope this helps!


The way forward always starts with a minimal test.

In reply to Re: Sorting and ranking by 1nickt
in thread Sorting and ranking by Anonymous Monk

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.