在 Perl 中如何按二级哈希值排序?
my $hash_ref = {
one => { val => 1, name => 'one' },
three => { val => 3, name => 'three'},
two => { val => 2, name => 'two' },
};
我想对 $hash_ref
进行排序,以便 foreach 可以按
$hash_ref->{$key}->{'val'}
one
two
three
任何建议对它们进行排序?
my $hash_ref = {
one => { val => 1, name => 'one' },
three => { val => 3, name => 'three'},
two => { val => 2, name => 'two' },
};
I would like to sort $hash_ref
such that a foreach would order them by
$hash_ref->{$key}->{'val'}
one
two
three
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
@sorted_list
是对已排序哈希元素的引用的数组:您可以像这样使用它:
输出:
@sorted_list
is an array of references to the sorted hash elements:You can use it like so:
Output:
哈希表没有任何特定的顺序。但是,您可以对数组中的键进行排序,并使用它来迭代散列:
您可以将任何您喜欢的内容定义为排序方法;有关详细信息,请参阅 perldoc -f sort。从序数数字文本到算术值的转换是通过 Lingua 完成的: :EN::Words2Nums (它也可以处理基数)。
Hash tables don't have any specific order. However, you can sort the keys in an array and use that to iterate through the hash:
You can define anything you like as a sort method; see perldoc -f sort for more details. Conversion from ordinal numerical text to arithmetic values is done with Lingua::EN::Words2Nums (it does cardinal numbers too).