2016-09-16 90 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);

相關問題