我试图对函数的结果进行排序,因为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";
Run Code Online (Sandbox Code Playgroud)
输出没有生成警告:
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
Run Code Online (Sandbox Code Playgroud)
1号是我的行为 - 没有输出.
我很惊讶2作品而1不作品.我认为他们是等同的.
我理解3和4,我用4来解决我的问题.
我真的很困惑5,特别是因为没有警告.
有人可以解释1和2之间有什么区别,为什么5输出函数的名称?
mob*_*mob 13
sort func()解析为sort func (),即()用例程对空列表[ ]进行排序func.
并且#5解析为sort ("func"),对包含(bareword)字符串的列表进行排序func.也许应该有关于此的警告,但事实并非如此.
Deparser输出:
$ 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
Run Code Online (Sandbox Code Playgroud)
Hun*_*len 11
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));
Run Code Online (Sandbox Code Playgroud)
所以在你的情况下你可以这样做:
@a = sort( func() );
Run Code Online (Sandbox Code Playgroud)