2016-09-16 89 views
2

请解释为什么这些Perl函数被称为的方式高于函数的定义确定它们是否运行。为什么你可以在声明sub foo之前调用foo()和&foo,但是你不能调用plain foo?

print "Why does this bare call to foo not run?\n"; 
foo; 
print "When this call to foo() does run?\n"; 
foo(); 
print "And this call to &foo also runs?\n"; 
&foo; 

sub foo { 
    print " print from inside function foo:\n"; 
} 

print "And this bare call to foo below the function definition, does run?\n"; 
foo; 

回答

7

如果解析器知道有问题的标识符指向某个函数,那么只能在函数调用中省略括号。

你的第一个foo;不是函数调用,因为解析器还没有看到sub foo(而foo不是内置的)。

如果您在顶部使用use strict; use warnings;,则会将其标记为错误。

3

报价perldata

有,好像它是带引号的字符串中的语法没有其他的解释将被视为一个字。这些被称为“裸语”。

这意味着foo等于"foo"如果没有子声明给它一个替代解释。

$ perl -e'my $x = foo; print("$x\n");' 
foo 

这被认为是误功能,因此它是由use strict;为了赶上错别字禁用(或更具体地,通过use strict qw(subs);)。

$ perl -e'use strict; my $x = foo; print("$x\n");' 
Bareword "foo" not allowed while "strict subs" in use at -e line 1. 
Execution of -e aborted due to compilation errors. 

始终使用use strict; use warnings qw(all);

相关问题