问题描述
我得到以下代码:
sub deg2rad ($;$) { my $d = _DR * $_[0];$_[1] ?$d : rad2rad($d) }
谁能告诉我 $;$
是什么意思?
Can anyone tell me what $;$
means?
推荐答案
子声明后面括号中的内容称为原型.它们在 perlsub 中有解释.通常,您可以使用它们来限制编译时参数检查.
The stuff in parenthesis behind a sub declaration is called a prototype. They are explained in perlsub. In general, you can use them to have limit compile-time argument checking.
特定的 ($;$)
用于强制参数.
The particular ($;$)
is used for mandatory arguments.
分号 (;) 将强制参数与可选参数分开.在 @ 或 % 之前是多余的,它会吞噬其他所有内容
所以在这里,必须使用至少一个参数来调用 sub,但可能还有第二个参数.
So here, the sub has to be called with at least one argument, but may have a second one.
如果你用三个参数调用它,它会抛出一个错误.
If you call it with three arguments, it will throw an error.
use constant _DR => 1;
sub rad2rad {@_}
sub deg2rad ($;$) { my $d = _DR * $_[0]; $_[1] ? $d : rad2rad($d) }
print deg2rad(2, 3, 4);
__END__
Too many arguments for main::deg2rad at scratch.pl line 409, near "4)"
Execution of scratch.pl aborted due to compilation errors.
请注意,原型不适用于像 $foo->frobnicate()
这样的方法调用.
一般来说,原型在现代 Perl 中被认为是不好的做法,只有在您确切地知道自己在做什么时才应该使用.
In general, prototypes are considered bad practice in modern Perl and should only be used when you know exactly what you are doing.
简明扼要的方式Sidhekin使用了在他们下面的评论中总结得很好:
The short and to the point way The Sidhekin used in their comment below sums it up nicely:
他们被认为是不好的做法的最重要原因是不确切知道自己在做什么的人,正在尝试使用他们为了一些他们不喜欢的东西.
有关该主题的详细解释和讨论,请参阅此问题及其答案.
See this question and its answers for detailed explanations and discussion on that topic.
这篇关于$;$ 在 Perl 函数定义中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!