【问题标题】:Trying to understand Perl sorting the result of a function试图理解 Perl 对函数结果进行排序
【发布时间】:2013-06-26 14:30:24
【问题描述】:

我试图对函数的结果进行排序,如sort func(); 并因为没有返回任何内容而被烧毁。我猜 Perl 认为函数调用是一个没有数据的排序例程。

Perldoc 说第二个参数可以是子例程名称或代码块。我将 func() 视为调用,而不是名称。我认为这根本不是 DWIMMY。

为了进一步探索它是如何工作的,我写了这个:

use strict;
use warnings;

sub func {
    return qw/ c b a /;
}

my @a;

@a = sort func();
print "1. sort func():    @a\n"; 

@a = sort &func;
print "2. sort &func:     @a\n"; 

@a = sort +func();
print "3. sort +func():   @a\n"; 

@a = sort (func());
print "4. sort (func()):  @a\n"; 

@a = sort func;
print "5. sort func:      @a\n"; 

输出,没有产生警告:

1. sort func():
2. sort &func:     a b c
3. sort +func():   a b c
4. sort (func()):  a b c
5. sort func:      func

数字 1 是让我感到困惑的行为 - 没有输出。

我很惊讶 2 有效而 1 无效。我认为它们是等价的。

我理解 3 和 4,我用 4 来解决我的问题。

我真的对 5 感到困惑,尤其是考虑到没有任何警告。

谁能解释一下 1 和 2 有什么区别,为什么 5 输出函数的名称?

【问题讨论】:

  • 两个很好的答案,希望我能同时选择。谢谢!

标签: perl


【解决方案1】:

sort func() 解析为 sort func (),即使用例程 func 对空列表 [()] 进行排序。

而#5 解析为sort ("func"),对包含(裸字)字符串func 的列表进行排序。也许应该对此发出警告,但没有。


解析器输出:

$ perl -MO=Deparse -e '@a1 = sort func();' -e '@a2=sort &func;' \
    -e '@a3=sort +func();' -e '@a4=sort (func());' -e '@a5=sort func;'
@a1 = (sort func ());
@a2 = sort(&func);
@a3 = sort(func());
@a4 = sort(func());
@a5 = sort('func');
-e syntax OK

【讨论】:

  • 我认为该位置的裸词会产生警告?
  • 裸词应该被use strict 'subs'捕获,它们不会发出警告。但这里似乎有一个错误......
【解决方案2】:

perldoc 中有一个部分准确显示了如何对函数调用的返回进行排序:http://perldoc.perl.org/functions/sort.html

警告:对函数返回的列表进行排序时需要注意语法。如果要对函数调用 find_records(@key) 返回的列表进行排序,可以使用:

@contact = sort { $a cmp $b } find_records @key;
@contact = sort +find_records(@key);
@contact = sort &find_records(@key);
@contact = sort(find_records(@key));

所以在你的情况下你可以这样做:

@a = sort( func() );

【讨论】:

    猜你喜欢
    • 2017-08-28
    • 2014-01-17
    • 2020-06-24
    • 2011-12-09
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多