2016-09-21 48 views
8

爲Perl子程序,如果傳遞0參數,我可以使用4種形式來調用它。但是,如果通過1個或多個參數,還有一種形式,我不能使用,請參閱以下內容:爲什麼`&name arg1 arg2 ...`語法不能用來調用Perl子例程?

sub name 
{ 
    print "hello\n"; 
} 
# 4 forms to call 
name; 
&name; 
name(); 
&name(); 

sub aname 
{ 
     print "@_\n"; 
} 
aname "arg1", "arg2"; 
#&aname "arg1", "arg2"; # syntax error 
aname("arg1", "arg2"); 
&aname("arg1", "arg2"); 

錯誤輸出

String found where operator expected at tmp1.pl line 16, near "&aname "arg1"" 
    (Missing operator before "arg1"?) 
syntax error at tmp1.pl line 16, near "&aname "arg1"" 
Execution of tmp1.pl aborted due to compilation errors. 

有人可以解釋從編譯器的輸出中的錯誤觀點看法?我不明白爲什麼它抱怨失蹤的運營商。

感謝

+3

你有一個很好的答案。有關使用'&'進行更多討論,請參見['這篇文章'](http://stackoverflow.com/questions/1347396/when-should-i-use-the-to-call-a- perl-subroutine)和['this post'](http://stackoverflow.com/questions/8912049/difference-between-function-and-function-in-perl)和['this post'](http: //stackoverflow.com/questions/6706882/using-ampersands-and-parens-when-calling-a-perl-sub)...並且可能還有其他人。 – zdim

+1

@zdim只是想知道,爲什麼你把代碼標記中的鏈接? – simbabque

+0

@simbabque哈,好點。我想這是爲了讓它們更加明顯,突出顯示。真的不知道。從來沒有真正將其視爲「代碼標記」(你是對的,它是) - 但更重要的是。 – zdim

回答

13

它記錄了perlsub

要調用的子程序:

 NAME(LIST); # & is optional with parentheses. 
     NAME LIST;  # Parentheses optional if predeclared/imported. 
     &NAME(LIST); # Circumvent prototypes. 
     &NAME;   # Makes current @_ visible to called subroutine. 

隨着&NAME "arg",PERL看到&NAME() "ARG",所以它認爲有一個運營商子之間失蹤呼叫和「ARG」。

在Perl 5中,大多數情況下不需要&

相關問題