参见英文答案 >
What does the function declaration “sub function($$)” mean? 2个
我得到以下代码:
我得到以下代码:
sub deg2rad($; $){my $d = _DR * $_ [0]; $_ [1]? $d:rad2rad($d)}
任何人都能告诉我$; $是什么意思?
解决方法
子声明后面的括号中的内容称为原型.它们在
perlsub中进行了解释.通常,您可以使用它们来限制编译时参数检查.
特定($; $)用于强制参数.
A semicolon (; ) separates mandatory arguments from optional arguments. It is redundant before @ or %,which gobble up everything else
所以在这里,sub必须至少用一个参数调用,但可能有第二个参数.
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中被认为是不好的做法,只有在您确切知道自己在做什么时才应该使用原型.
The Sidhekin使用的短路和分路in their comment below很好地总结了它:
The most important reason they’re considered bad practice,is that
people who don’t know exactly what they are doing,are trying to use
them for something that they’re not.
有关该主题的详细说明和讨论,请参阅this question及其答案.