【问题标题】:sort keys in hash of array by the number of elements in the array按数组中元素的数量对数组哈希中的键进行排序
【发布时间】:2013-03-21 06:41:06
【问题描述】:

我有一个数组散列。

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

数组中的值本身并不重要。我想按数组的大小按降序对键进行排序。输出应该是这样的。

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

我不知道为什么这不起作用。

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

【问题讨论】:

    标签: arrays perl sorting hash


    【解决方案1】:

    您必须比较数组大小:

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

    【讨论】:

    • { @{ $HoA{$b} } &lt;=&gt; @{ $HoA{$a} } } 也可以工作(没有scalar),因为数字比较强制使用标量上下文。
    猜你喜欢
    • 2015-04-13
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    • 1970-01-01
    • 2011-03-10
    • 2020-04-05
    • 2011-04-26
    相关资源
    最近更新 更多