说我希望通过在另一个哈希(%hash
)中查找比较来排序数组哈希(%comparator
):
我认为以下内容可行,但事实并非如此。
for ($bin_ix=1; $bin_ix<scalar(keys(%cluster_bins)); $bin_ix++) {
$hash{$bin_ix} = sort {$comparator{$a} <=> $comparator{$b} $hash{$bin_ix}};
}
抱怨:Missing operator before %hash
。我错过了什么?
答案 0 :(得分:4)
实际上,它说
Scalar found where operator expected at -e line 2, near "} $hash"
(Missing operator before $hash?)
它抱怨你错位}
,但还有第二个问题:$hash{$bin_ix}
仅仅是对数组的引用,而不是数组。你想要
@{ $hash{$bin_ix} } =
sort { $comparator{$a} <=> $comparator{$b} }
@{ $hash{$bin_ix} };
答案 1 :(得分:2)
Ikegami已经回答了你的直接问题,但我想指出,如果你确实想要在%hash
中对所有数组进行排序,那么编写循环的方法就更简单了将是:
foreach my $array ( values %hash ) {
@$array = sort { $comparator{$a} <=> $comparator{$b} } @$array;
}
即使您确实只想对从1
到scalar keys %cluster_bins
的键的数组进行排序,TLP的建议仍然会更清晰:
foreach my $bin_idx ( 1 .. keys %cluster_bins ) {
my $array = $hash{ $bin_idx };
@$array = sort { $comparator{$a} <=> $comparator{$b} } @$array;
}