Perl解析器使用sort和uniq进行巧妙的操作

Perl解析器使用sort和uniq进行巧妙的操作,perl,Perl,嗨,我是Perl的新手。我很难理解运算符的优先级。我在维基百科的Ruby页面上找到了一个程序 "Nice Day Isn't It?".downcase.split("").uniq.sort.join # => " '?acdeinsty" 我在Perl中也尝试了同样的方法,但解析器的操作非常复杂。我有以下程序 use strict; use warnings; use List::MoreUtils qw(uniq distinct) ; my $h

嗨,我是Perl的新手。我很难理解运算符的优先级。我在维基百科的Ruby页面上找到了一个程序

"Nice Day Isn't It?".downcase.split("").uniq.sort.join # => " '?acdeinsty"
我在Perl中也尝试了同样的方法,但解析器的操作非常复杂。我有以下程序

    use strict;
    use warnings;
    use List::MoreUtils qw(uniq distinct) ;

    my $hello = q/Nice Day Isn't It?/ ;

    print join ('', sort ( List::MoreUtils::uniq (split(//, lc $hello ))));  # &List::MoreUtils::uniq parses correctly and I need to include & before call.

    print "\n";

    print join('', sort( List::MoreUtils::uniq(split(//, lc $hello, 0))));
输出:

   '?acdeiiinnstty
 '?acdeinsty
此外,我还尝试查看Perl如何使用B::Deparse模块解析代码,下面是输出

perl -MO=Deparse test.pl
use List::MoreUtils ('uniq', 'distinct');
use warnings;
use strict 'refs';
my $hello = q[Nice Day Isn't It?];
print join('', (sort List::MoreUtils::uniq split(//, lc $hello, 0)));
print "\n";
print join('', sort(&List::MoreUtils::uniq(split(//, lc $hello, 0))));
test.pl syntax OK
当我简单地使用uniq时,我也会收到警告,因为我可能会与将来保留的关键字冲突。任何关于列表优先级和关联性的有用链接都将非常有用。我参考了perlop术语和列表运算符部分

提前感谢。

查看文档以了解更多信息。如果您向它传递一个子名称,它将尝试使用该子名称进行排序

这就是为什么以下各项有所不同:

print join '', sort(uniq(split //, lc $hello));
# Prints:  ?acdeinsty

print join '', sort uniq(split //, lc $hello);
# Prints: nice day isn't it?
第二个相当于:

print join '', sort {uniq} (split //, lc $hello);
对于所有测试,
uniq
函数将返回
0
,声明每个字符相等。因此,
sort
将保持相同的顺序,将上述代码减少为:

print join '', split //, lc $hello;
防止
排序
使用下一个子集作为比较器的一个技巧是在子集名称(tympapec)前面加一个
+
符号:


@mpapec的可能副本。对不起,我没有查到搜索结果。此外,List::MoreUtils::uniq和后面的parantasis之间的空格似乎是一个陷阱,因为空格使uniq成为排序函数,而没有空格则是一个单独的函数。谢谢@Miller。我查阅了文档,但不知道如何将uniq作为单独的函数而不是用于排序的函数进行更改。mpapec应答打印连接(“”,排序(+uniq(拆分(/,lc$hello)));太给出了答案。是的,你可以使用更多的括号,或者使用mpapec建议的技巧。在我的回答中补充了这一点。
print join '', sort +uniq split //, lc $hello;