in reply to Re: Sorting and ranking
in thread Sorting and ranking

$rank[ $data{$_} ] .= "$_\n" for sort keys %data; defined and $n += print s/^/$n - /gmr for reverse @rank;

Clever as always :-) It should be noted, however, that memory usage (and speed) gets worse for increasingly large values in the hash, since it causes @rank to grow accordingly.

Replies are listed 'Best First'.
Re^3: Sorting and ranking
by tybalt89 (Monsignor) on Jan 23, 2018 at 00:50 UTC

    Of course. One of the beauties of perl, however, is the ability to easily switch over to using a hash. The sort will have to be explicit, of course. instead of getting it as a freebie with the array.

    As a bonus, you get the ability to properly handle negative and/or non-integer values.

    #!/usr/bin/perl # http://perlmonks.org/?node_id=1207623 use strict; use warnings; my %data = ( 'car' => 180, 'motorcycle' => 150, 'skate' => 150, 'bird' => 120, ); my ($n, %rank) = 1; $rank{ $data{$_} + 0 } .= "$_\n" for sort keys %data; $n += print s/^/$n - /gmr for @rank{ sort { $b <=> $a } keys %rank };