Perl - 使用或不使用“&”(&符号)调用子例程之间的区别[重复]

问题描述 投票:0回答:2

Perl 中接下来的两行有什么区别:

PopupMsg("Hello");

&PopupMsg("Hello");

...

sub PopupMsg
{
    subroutines code here...
}

请注意,在某些情况下我必须使用第一行,而在某些情况下必须使用第二行,否则我会收到错误。

perl subroutine
2个回答
8
投票

使用 & 符号

&
调用子例程是不好的做法。如果您使用括号或预先将符号声明为子例程名称,则该调用将可以正常编译。

当您将子例程作为数据项处理时,例如,要引用它时,“&”是必需的。

my $sub_ref = \&PopupMsg;
$sub_ref->(); # calling subroutine as reference.

4
投票

参见 http://perldoc.perl.org/perlsub.html:

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

原型在 http://perldoc.perl.org/perlsub.html#Prototypes 中进一步解释。

© www.soinside.com 2019 - 2024. All rights reserved.