in reply to Sorting and ranking
The code prints 1,2,3,4,
The code you've posted doesn't print that, it prints 'syntax error at 1207623.pl line 10, near "@sorted["'. Please post the actual code you are running. (How do I post a question effectively?) Also, always Use strict and warnings.
If I assume you meant my @sorted; @sorted[...] = ...;, then the code runs, but I think you're making things a little too complicated with the various arrays - note that the comparison $sorted[$count] != $sorted[$count-1] should always be true because you've assigned @sorted[...] = 1..@keys; that is, all the values of @sorted are different. Have a look at the Basic debugging checklist, especially the advice to use Data::Dumper or Data::Dump to look at your data structures.
Here's one way to approach this. I first sort the keys (see also How do I sort an array by (anything)?), and then just run through those keys and look at the current and previous value, increasing the rank if they differ. (This assumes no undef values in the hash, since I use that value to keep track if there was a $previous value or this is the first.)
use warnings; use strict; use Data::Dump; my %data = ( 'car' => 180, 'motorcycle' => 150, 'skate' => 150, 'bird' => 120, ); my @keys = sort { $data{$b} <=> $data{$a} or $a cmp $b } keys %data; my ($prev,$rank); for my $k (@keys) { $rank++ unless defined($prev) && $prev==$data{$k}; dd $k, $data{$k}, $rank; $prev = $data{$k}; } __END__ ("car", 180, 1) ("motorcycle", 150, 2) ("skate", 150, 2) ("bird", 120, 3)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Sorting and ranking
by Anonymous Monk on Jan 21, 2018 at 13:22 UTC |