如何自然地对哈希键排序?
问题描述:
我有一个Perl哈希,其键以数字开头或为数字.
I have a Perl hash whose keys start with, or are, numbers.
如果我使用
foreach my $key (sort keys %hash) {
print $hash{$key} . "\n";
}
列表可能显示为
0
0001
1000
203
23
代替
0
0001
23
203
1000
答
foreach my $key (sort { $a <=> $b} keys %hash) {
print $hash{$key} . "\n";
}
sort操作采用一个可选的比较子例程"(作为代码块(如我在此处所做的那样)或子例程的名称).我提供了一个内联比较,它使用内置的数字比较运算符'< =>'将键视为数字.
The sort operation takes an optional comparison "subroutine" (either as a block of code, as I've done here, or the name of a subroutine). I've supplied an in-line comparison that treats the keys as numbers using the built-in numeric comparison operator '<=>'.