问题描述
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,它将给出一个子例程的名称,该子例程返回一个小于,等于或大于0的整数,具体取决于列表元素的排序方式.
第一个示例中的uniq
被用作裸字,它指定要用于排序的子项的名称,而qw(b a a)
是要排序的列表-您不是uniq
-列出列表(可以这么说),但使用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"之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!