sort keys in hash of array by the number of elements in the array

人走茶凉 提交于 2019-12-22 12:51:37

问题


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";
}


来源:https://stackoverflow.com/questions/15722286/sort-keys-in-hash-of-array-by-the-number-of-elements-in-the-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!