我怎样才能自然地对散列键进行排序?

编程入门 行业动态 更新时间:2024-10-26 13:23:50
本文介绍了我怎样才能自然地对散列键进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我使用,

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

更多推荐

我怎样才能自然地对散列键进行排序?

本文发布于:2023-06-10 05:44:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/608237.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自然地   散列键

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!