【问题标题】:Perl parser acts wierdly with sort and uniqPerl 解析器对 sort 和 uniq 的行为很奇怪
【发布时间】:2014-03-21 20:07:42
【问题描述】:

嗨,我是 Perl 的新手。我无法理解运算符的优先级。我在 Ruby 的 Wikipedia 页面中找到了一个程序

"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 术语和列表运算符部分。

提前致谢。

【问题讨论】:

  • @mpapec 。抱歉,我不去查搜索。此外,List::MoreUtils::uniq 和后面的括号之间的空格似乎是带有空格的陷阱,使 uniq 成为排序函数,而没有空格则成为单独的函数。

标签: perl


【解决方案1】:

查看sort 的文档。如果您传递一个子名称,它会尝试使用该子名称进行排序。

这就是为什么以下内容不同:

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;

防止sort 使用下一个子作为比较器的一个技巧是在子名称(ty mpapec)前面放置一个+ 符号:

print join '', sort +uniq split //, lc $hello;

【讨论】:

  • 谢谢@Miller。我查阅了文档,但不知道如何将 uniq 更改为单独的函数而不是用于排序的函数。 mpapec answer print join ('', sort (+uniq (split(//, lc $hello ))));也给出了答案。
  • 是的,您可以使用更多的括号,或者使用 mpapec 建议的技巧。将其添加到我的答案中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
  • 1970-01-01
  • 2020-02-12
  • 2014-12-14
相关资源
最近更新 更多