我怎样才能自然地对散列键进行排序? [英] How can I sort a hash's keys naturally?

查看:98
本文介绍了我怎样才能自然地对散列键进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果我使用,

  foreach my $ key(sort keys%hash){
print $ hash {$ key}。 \\\
;
}

列表可能会显示为,

  0 
0001
1000
203
23

而不是

  0 
0001
23
203
1000


解决方案

  foreach my $ key(sort {$ a< => $ b} keys%hash){
print $ hash {$ key}。 \\\
;





$ b

排序操作需要一个可选的比较子程序(作为代码,正如我在这里所做的,或者子例程的名称)。我提供了一个内联比较,它使用内置的数字比较运算符'< =>'将键作为数字对待。


I have a Perl hash whose keys start with, or are, numbers.

If I use,

foreach my $key (sort keys %hash) {
    print $hash{$key} . "\n";
}

the list might come out as,

0
0001
1000
203
23

Instead of

0
0001
23
203
1000

解决方案

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

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 '<=>'.

这篇关于我怎样才能自然地对散列键进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆