Search code examples
perlsortingranking

Perl: Sorting the values of a hash and putting the result in a new hash where the keys are position in ranking


I have the following structure, %hash:

$VAR1 = {
           1 => 5,
           3 => 1,
           2 => 4,
           4 => 9,

        };

The keys of this hash represent id and the values represent number of access: id => number of access

I want to sort this using the number of access, in descending order, and store it in another hash. But I want the values to be the id this time. The keys should be the position in the ranking: position in raking (from 1 to n) => id

In this particular case:

$VAR2 = {
           1 => 4,
           2 => 1,
           3 => 2,
           4 => 3,
        };

How should I do this?


Solution

  • You can use sort in a foreach loop.

    my %hash = (
    1 => 5,
    3 => 1,
    2 => 4,
    4 => 9,
    );
    
    my %hash2;
    my $count = 1;
    foreach my $key(sort{$hash{$b} <=> $hash{$a}} keys %hash){
        $hash2{$count++} = $key;
    }
    
    use Data::Dumper;
    print Dumper(\%hash2);
    

    OR

    You can use map to do the looping as David mentioned. I added foreach for simplicity.

    my %hash2 = map {$count++ => $_} sort{$hash{$b} <=> $hash{$a}} keys %hash;