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)

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