perl List :: AllUtils uniq&分类

时间:2016-07-25 11:08:19

标签: perl

试试这个:

perl -Mv5.14 -MList::AllUtils=uniq -E 'my(@x) = qw(2 3 1 2); say "@x"; my(@y) = uniq @x; say "@y"'

正确打印

2 3 1 2
2 3 1

现在想要排序的输出,所以尝试了:

perl -Mv5.14 -MList::AllUtils=uniq -E 'my(@x) = qw(2 3 1 2); say "@x"; my(@y) = sort uniq @x; say "@y"'

令人惊讶的是它打印出来:

2 3 1 2
2 1 3 2

切换uniqsort

的顺序
perl -Mv5.14 -MList::AllUtils=uniq -E 'my(@x) = qw(2 3 1 2); say "@x"; my(@y) = uniq sort @x; say "@y"'

给出正确的结果

2 3 1 2
1 2 3

因此,使用MO=Deparse比较它们。

第一名:

perl -MO=Deparse -Mv5.14 -MList::AllUtils=uniq -E 'my(@x) = qw(2 3 1 2); say "@x"; my(@y) = uniq @x; say "@y"'
sub BEGIN {
    require v5.14;
}
use List::AllUtils (split(/,/u, 'uniq', 0));
use strict;
use feature 'current_sub', 'evalbytes', 'fc', 'postderef_qq', 'say', 'state', 'switch', 'unicode_strings', 'unicode_eval';
my(@x) = ('2', '3', '1', '2');
say join($", @x);
my(@y) = &uniq(@x);
say join($", @y);
-e syntax OK

第二个:

perl -MO=Deparse -Mv5.14 -MList::AllUtils=uniq -E 'my(@x) = qw(2 3 1 2); say "@x"; my(@y) = sort uniq @x; say "@y"'
sub BEGIN {
    require v5.14;
}
use List::AllUtils (split(/,/u, 'uniq', 0));
use strict;
use feature 'current_sub', 'evalbytes', 'fc', 'postderef_qq', 'say', 'state', 'switch', 'unicode_strings', 'unicode_eval';
my(@x) = ('2', '3', '1', '2');
say join($", @x);
my(@y) = (sort uniq @x);
say join($", @y);
-e syntax OK

第三

perl -MO=Deparse -Mv5.14 -MList::AllUtils=uniq -E 'my(@x) = qw(2 3 1 2); say "@x"; my(@y) = uniq sort @x; say "@y"'
sub BEGIN {
    require v5.14;
}
use List::AllUtils (split(/,/u, 'uniq', 0));
use strict;
use feature 'current_sub', 'evalbytes', 'fc', 'postderef_qq', 'say', 'state', 'switch', 'unicode_strings', 'unicode_eval';
my(@x) = ('2', '3', '1', '2');
say join($", @x);
my(@y) = &uniq(sort(@x));
say join($", @y);
-e syntax OK

不同之处在于如何调用uniq子例程:

my(@y) = (sort uniq @x);  # sort uniq @x
my(@y) = &uniq(sort(@x)); # uniq sort @x

我理解,uniq是由List::AllUtils提供的子程序,而sort是内置函数,但使用uniq作为:

my(@y) = &uniq(sort(@x));

对我来说似乎并不具有直观性。

我必须以&uniq(...)形式使用它,例如&和括号? Coudl有人请添加更多信息吗?

1 个答案:

答案 0 :(得分:2)

如果您使用use strictuse warnings运行它,它会告诉您出了什么问题。

use strict;
use warnings;
use feature 'say';
use List::AllUtils 'uniq';

my (@x) = qw(2 3 1 2);
say "@x";
my (@y) = sort uniq @x;
say "@y";

这会发出警告 Sort子程序未在返回单个值。 sort认为uniq是用于对列表进行排序的子例程。

The sort documentation解释了这一点。

  

排序SUBNAME LIST
  排序列表
  排序列表

您也可以给它一个子名称。使用该子名称directy(即不作为字符串或代码引用)有点违反直觉,但这应该是它应该如何。甚至在文档中都有一个例子。

# sort using explicit subroutine name
sub byage {
    $age{$a} <=> $age{$b};  # presuming numeric
}
my @sortedclass = sort byage @class;

因此,在这种情况下,它会将您的uniq视为_call uniq(@x),并使用默认的sort行为对返回值进行排序,而是排序{{1使用@x作为排序函数

您可以使uniq忽略子名称并使用返回值代替sort符号。

+

现在没有警告。 my (@x) = qw(2 3 1 2); say "@x"; my (@y) = sort +uniq @x; say "@y"; __END__ 2 3 1 2 1 2 3 也有效,并且更易于阅读。