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!
Output: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__
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!
In reply to Re: Sorting and ranking
by 1nickt
in thread Sorting and ranking
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |