带“&”(与号)和不带[duplicate]的Perl子例程有什么区别

xvw2m8pv  于 2022-11-15  发布在  Perl
关注(0)|答案(2)|浏览(152)

此问题在此处已有答案

Difference between &function and function() in perl [duplicate](2个答案)
八年前就关门了。
Perl中下面两行代码的区别是什么:

PopupMsg("Hello");

&PopupMsg("Hello");

...

sub PopupMsg
{
    subroutines code here...
}

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

1hdlvixo

1hdlvixo1#

使用&符号&调用子例程是不好的做法。如果使用括号或将符号预声明为子例程名称,则调用将编译良好。
当您将子例程作为数据项处理时(例如,获取对它的引用),&号是必需的。

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

guicsvcw2#

请参阅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.

原型将在www.example.com中进一步说明http://perldoc.perl.org/perlsub.html#Prototypes。

相关问题