对 Perl 数值数组进行排序
我有一个如下所示的数组:
array[0]: 6 8
array[1]: 12 9 6
array[2]: 33 32 5
array[3]: 8 6
我想对此数组进行排序,使其看起来像这样:
array[0]: 6 8
array[1]: 6 9 12
array[2]: 5 32 33
array[3]: 6 8
我知道我可以使用 @newarray = sort {$a cmp $b} @array; 对该数组进行排序>,但我还需要对每行中的元素进行排序。我怎样才能做到这一点?
I have an array which looks like this:
array[0]: 6 8
array[1]: 12 9 6
array[2]: 33 32 5
array[3]: 8 6
I want to sort this array so that it looks like this:
array[0]: 6 8
array[1]: 6 9 12
array[2]: 5 32 33
array[3]: 6 8
I know I can sort the array with @newarray = sort {$a cmp $b} @array;
, but I need to sort the elements in each line as well. How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更新 2021-03-16:亲爱的未来访客,我已经接受了答案,而且我仍在获得投票,但是 @FMc 的解决方案显然比我的好。 (FMc 和 dalton 有相同的答案,但据我所知,FMc 首先到达那里。)
无论如何,如果您遇到这样的情况,请使用 Perl 的内置 map 而不是我最初对自定义子例程的回答。
原始答案:假设您有一个字符串数组,并且您想要的只是对每个字符串进行排序,就好像它是数字的子数组一样(但将其保留为字符串?):
Update 2021-03-16: Dear future visitors, I have the accepted answer, and I'm still getting upvotes, but @FMc's solution is clearly better than mine. (FMc and dalton have the same answer, but as far as I can tell, FMc got there first.)
In any case, if you have a situation like this use Perl's built-in map rather than my original answer of a custom subroutine.
Original answer: Assuming that you have an array of strings there, and that all you want is to sort each string as if it were a sub-array of numbers (but leave it a string?):
您还可以使用地图来解决它:
输出:
You could also solve it using map:
Outputs:
您有一个要转换的项目列表。这是 map 的完美候选者。另请注意 split 的默认行为:它在
$_,在删除前导空格后按空格分割。
You have a list of items that you want to transform. That's a perfect candidate for map. Also note the default behavior of split: it operates on
$_
, splitting on whitespace, after removing leading whitespace.