我应该调用没有参数的 Perl 子程序作为海洋()还是海洋? [英] Should I call Perl subroutines with no arguments as marine() or marine?
问题描述
根据我下面的示例代码,调用子程序有两种样式:subname
和 subname()
.
As per my sample code below, there are two styles to call a subroutine: subname
and subname()
.
#!C:\Perl\bin\perl.exe
use strict;
use warnings;
use 5.010;
&marine(); # style 1
&marine; # style 2
sub marine {
state $n = 0; # private, persistent variable $n
$n += 1;
print "Hello, sailor number $n!\n";
}
如果调用中没有参数,&marine();
或 &marine;
哪个是更好的选择?
Which one, &marine();
or &marine;
, is the better choice if there are no arguments in the call?
推荐答案
在学习 Perl,这个例子来自哪里,我们刚开始向您展示子程序.我们只告诉您使用 &
以便您,作为开始的 Perler,不会遇到定义与 Perl 内置同名的子例程的问题,然后想知道为什么它不起作用.前面的 &
总是调用你定义的子程序.初学者经常创建他们自己的子程序 log
来打印消息,因为他们习惯于在他们使用的其他技术中这样做.在 Perl 中,这是内置的数学函数.
In Learning Perl, where this example comes from, we're at the very beginning of showing you subroutines. We only tell you to use the &
so that you, as the beginning Perler, don't run into a problem where you define a subroutine with the same name as a Perl built-in then wonder why it doesn't work. The &
in front always calls your defined subroutine. Beginning students often create their own subroutine log
to print a message because they are used to doing that in other technologies they use. In Perl, that's the math function builtin.
在您习惯使用 Perl 并了解 Perl 内置程序后(浏览 perlfunc),删除 &
.&
有一些你几乎不需要的特殊魔法:
After you get used to using Perl and you know about the Perl built-ins (scan through perlfunc), drop the &
. There's some special magic with &
that you hardly ever need:
marine();
如果您预先声明了子例程,您可以省略 ()
,但我通常将 ()
留在那里,即使是空参数列表也是如此.由于您向 Perl 提示 marine
是一个子例程名称,因此它更健壮一些.对我来说,我更快地认识到这是一个子程序.
You can leave off the ()
if you've pre-declared the subroutine, but I normally leave the ()
there even for an empty argument list. It's a bit more robust since you're giving Perl the hint that the marine
is a subroutine name. To me, I recognize that more quickly as a subroutine.
这篇关于我应该调用没有参数的 Perl 子程序作为海洋()还是海洋?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!