如何自然地对哈希键排序? [英] How can I sort a hash's keys naturally?

查看:100
本文介绍了如何自然地对哈希键排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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 '<=>'.

这篇关于如何自然地对哈希键排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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