sort keys in hash of array by the number of elemen

2019-05-27 03:06发布

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条回答
做个烂人
2楼-- · 2019-05-27 03:36

You must compare the array sizes:

foreach my $key ( sort { scalar @{$HoA{$b}} <=> scalar @{$HoA{$a}}} keys %HoA ) {
    print "$key\n";
}
查看更多
登录 后发表回答