我有一个数组哈希,我想按数组大小排序.
到目前为止,这是我的代码:
use strict;
use warnings;
my %hash_array = (
"array_1" => ["apple", "ball", "cat"],
"array_2" => ["def", "leppard", "rocks", "too"],
"array_3" => ["italian", "pastry", "missing", "cherry", "top"],
);
# Length of array_1
my $array_1_size = @{$hash_array{"array_1"}};
print "Should print three: $array_1_size\n";
# Found this here: https://stackoverflow.com/questions/15722286
# But my result remains unsorted
foreach my $key ( sort { $hash_array{$b} <=> $hash_array{$a}} keys %hash_array ) {
print "key: $key\n";
}
Run Code Online (Sandbox Code Playgroud)
我理解如何获得单个数组的大小,但我不确定如何将它与sort函数结合起来.
我从这里复制了最后一个foreach块,但该解决方案对我不起作用,因为我的输出没有被订购.我对最后一段代码有一些疑问:
你很亲密 如上所述,您正在比较数组引用,它们或多或少是内存地址.我稍微修改了你的代码,以便为你提供所需内容:
foreach my $key ( sort { scalar(@{$hash_array{$b}}) <=> scalar(@{$hash_array{$a}}) } keys %hash_array ) {
print "key: $key\n";
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1001 次 |
最近记录: |