sort keys in hash of array by the number of elemen

2019-05-27 03:23发布

问题:

I have a hash of arrays.

%HoA = (
    'C1' =>  ['1', '3', '3', '3'],
    'C2' => ['3','2'],
    'C3' => ['1','3','3','4','5','5'],
    'C4'  => ['3','3','4'],
    'C5' => ['1'],
);

The values in the array don't matter per se. I would like to sort the keys by the size of the array in descending order. The output should look like.

C3  # this key contains an array with the most elements
C1
C4
C2
C5  # this key contains an array with the least elements

I don't know why this isn't working.

foreach my $key ( sort { $HoA{$b} <=> $HoA{$a}} keys %HoA ) {
    print "$key\n";
}

回答1:

You must compare the array sizes:

foreach my $key ( sort { scalar @{$HoA{$b}} <=> scalar @{$HoA{$a}}} keys %HoA ) {
    print "$key\n";
}