“不是数字" "sort"中的错误在"uniq"之后 [英] "isn't numeric" error in "sort" after "uniq"

查看:96
本文介绍了“不是数字" "sort"中的错误在"uniq"之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

use List::MoreUtils 'uniq';
print join ", ", sort uniq ("b", "a", "a");

结果参数"a"不是在...处的数字排序

print join ", ", uniq sort ("b", "a", "a");

按预期工作.

print join ", ", sort {$a cmp $b} uniq ("b", "a", "a");

也可以工作-但是第一个示例有什么问题?

works too - but what is the problem with the first example?

推荐答案

该代码属于

That code falls under the sort invocation of

对SUBNAME列表进行排序

...
如果指定了SUBNAME,它将给出一个子例程的名称,该子例程返回一个小于,等于或大于0的整数,具体取决于列表元素的排序方式.

...
If SUBNAME is specified, it gives the name of a subroutine that returns an integer less than, equal to, or greater than 0 , depending on how the elements of the list are to be ordered.

第一个示例中的uniq被用作裸字,它指定要用于排序的子项的名称,而qw(b a a)是要排序的列表-您不是uniq-列出列表(可以这么说),但使用uniq作为该列表的排序功能.

The uniq in the first example is taken as a bareword that specifies the name of the sub to use for sorting and qw(b a a) is the list to sort -- you aren't uniq-ing the list (so to speak) but are using uniq as a sorting function for that list.

该错误消息是由于排序函数需要返回数字而uniq返回字符串.

The error message comes as a sorting function needs to return a number and uniq returns strings.

您已经找到一种使其工作的方法,并且还可以使用一元+

You've discovered one way to make it work, and can also use the unary +

say for sort +uniq(@ary);    # or: say for sort + uniq @ary;

由于+之后的内容被视为一个表达式,因此sort获得了求值列表.请参阅此帖子此帖子讨论一元+的此类用法.

since what follows + is treated as an expression, so sort gets the evaluated list. See this post and this post for discussion of such uses of the unary +.

或者通过和使用通行证

say for sort (uniq(@ary));

内部对也是必需的,因为在sort (uniq @ary)中,uniq被解释为该列表中的裸字,因此不合适.请注意,sort (uniq (@ary))将不起作用,因为多余的括号无关紧要,而我们又有了一个空词.所以这里的空间很重要!

Here the inner pair is also necessary since with sort (uniq @ary) the uniq is interpreted as a bareword in that list, thus out of place. Note that sort (uniq (@ary)) won't work since extra parens don't matter and we again have a bareword; so that space matters here!

之所以如此棘手,是因为sort灵活(模糊)的界面,在LIST 之前可选地加上LIST ,该裸字必须是子名称.最终依赖于解释器来解决其中的一些问题,然后我们必须保持精确.

This trickiness is due to sort's flexible (ambiguous) interface, taking a LIST optionally preceded by a bareword, which need be a sub name. It ends up relying on the interpreter to sort out some of that and then we have to be precise.

这篇关于“不是数字" "sort"中的错误在"uniq"之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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