Perl解析器使用sort和uniq进行了很好的操作

xtr*_*eak 3 perl

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

"Nice Day Isn't It?".downcase.split("").uniq.sort.join # => " '?acdeinsty"
Run Code Online (Sandbox Code Playgroud)

我在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))));
Run Code Online (Sandbox Code Playgroud)

输出:

   '?acdeiiinnstty
 '?acdeinsty
Run Code Online (Sandbox Code Playgroud)

我还试着看看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
Run Code Online (Sandbox Code Playgroud)

当我使用uniq时,我也会收到警告,因为我可能会与未来的保留关键字发生冲突.研究列表优先级和关联性的任何有用链接都将非常有用.我提到了perlop术语和列表操作符部分.

提前致谢.

Mil*_*ler 5

看看文档sort.如果你传递一个子名称,它将尝试使用它进行排序.

这就是为什么以下是不同的:

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

print join '', sort uniq(split //, lc $hello);
# Prints: nice day isn't it?
Run Code Online (Sandbox Code Playgroud)

第二个相当于:

print join '', sort {uniq} (split //, lc $hello);
Run Code Online (Sandbox Code Playgroud)

uniq函数将返回0所有测试,声称每个字符相等.因此sort将保持相同的顺序,将上面的代码简化为:

print join '', split //, lc $hello;
Run Code Online (Sandbox Code Playgroud)

保持sort使用下一个子作为比较器的一个技巧是+在子名称前面添加一个符号(ty mpapec):

print join '', sort +uniq split //, lc $hello;
Run Code Online (Sandbox Code Playgroud)