Use a HoA keyed by the value and sort that in descending order, incrementing rank for each key. Uncomment the Data::Dumper lines to see the structure of the HoA. The code

use strict; use warnings; use 5.022; # use Data::Dumper; my %data = ( car => 180, motorcycle => 150, skate => 150, bird => 120, ); my %byValue; push @{ $byValue{ $data{ $_ } } }, $_ for keys %data; # print Data::Dumper->Dumpxs( [ \ %byValue ], [ qw{ *byValue } ] ); my $rank; for my $descVal ( sort { $b <=> $a } keys %byValue ) { $rank ++; say qq{$rank - $_} for sort @{ $byValue{ $descVal } }; }

The output.

1 - car 2 - motorcycle 2 - skate 3 - bird

I hope this is helpful.

Update: An updated script to show the difference between "rank" and "place" as in "Fred and Mary were placed 3rd equal."

use strict; use warnings; use 5.022; my %data = ( car => 180, tortoise => 90, concorde => 300, motorcycle => 150, bird => 120, skate => 150, pedestrian => 100, rocket => 300, aeroplane => 210, unicycle => 175, sheep => 100, frog => 120, cow => 110, bus => 150, ); my %byValue; push @{ $byValue{ $data{ $_ } } }, $_ for keys %data; say q{Rank Place Item}; my $rank = 0; my $place = 1; for my $descVal ( sort { $b <=> $a } keys %byValue ) { $rank ++; my $count = scalar @{ $byValue{ $descVal } }; my $eq = $count > 1 ? q{=} : q{ }; printf qq{%3d%5d%1s %s\n}, $rank, $place, $eq, $_ for sort @{ $byValue{ $descVal } }; $place += $count; }

The output.

Rank Place Item 1 1= concorde 1 1= rocket 2 3 aeroplane 3 4 car 4 5 unicycle 5 6= bus 5 6= motorcycle 5 6= skate 6 9= bird 6 9= frog 7 11 cow 8 12= pedestrian 8 12= sheep 9 14 tortoise

Cheers,

JohnGG


In reply to Re: Sorting and ranking by johngg
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.