为什么语法“&name arg1 arg2 ...”不能用于调用 Perl 子例程?
why the syntax `&name arg1 arg2 ...` can't be used to call a Perl subroutine?
对于一个Perl子程序,如果传递0个参数,我可以使用4种形式来调用它。但是如果传递1个或多个参数,有一种形式我不能使用,请看下面:
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.
有人可以从编译器的角度解释错误输出吗?我不明白为什么它会抱怨缺少运算符。
谢谢
它记录在 perlsub:
To call subroutines:
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 中,大多数情况下您不需要 &
。
对于一个Perl子程序,如果传递0个参数,我可以使用4种形式来调用它。但是如果传递1个或多个参数,有一种形式我不能使用,请看下面:
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.
有人可以从编译器的角度解释错误输出吗?我不明白为什么它会抱怨缺少运算符。
谢谢
它记录在 perlsub:
To call subroutines:
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 中,大多数情况下您不需要 &
。