我最近一直在阅读有关Perl的内容,并且对于Perl如何处理传递给子例程的参数感到有些困惑.
在Python,Java或PHP等语言中,函数定义采用(伪代码)形式:
function myFunc(arg1, arg2) {
// Do something with arg1 and arg2 here
}
Run Code Online (Sandbox Code Playgroud)
然而在Perl中,它只是:
sub mySub {
# @_ holds all arguments passed
}
Run Code Online (Sandbox Code Playgroud)
据我了解,这是唯一的方法.
如果我想限制调用者只传递2个参数怎么办?
这不仅仅是Perl在其他语言(即Python,C等)中不允许任何变量数量参数吗?
在某些时候这不会成为问题吗?
其他语言中的所有默认参数号检查怎么样?是否必须在Perl中明确地做到这一点?例如
sub a_sub {
if (@_ == 2) {
# Continue function
}
else {
return false
}
}
Run Code Online (Sandbox Code Playgroud)我正在寻找一个通用的模块来解决验证子程序和方法参数的苦差事.:我已经通过在CPAN各种可能性进行扫描Params::Validate,Params::Smart,Getargs::Mixed,Getargs::Long,和其他几个人.
任何有关这些或其他模块的利弊的信息将不胜感激.谢谢.
我在类方法调用中使用命名参数,并想知道是否有最佳实践来确保没有传递未知参数.这就是我在做什么
sub classmethod {
my $self = shift;
my %args = (
"param1" => "default1",
"param2" => "default2",
@_
)
if (my @invalid = grep { !/^(param1|param2)$/ } keys %args) {
croak "received unknown arg(s) ".join(",", @invalid)." from ".caller();
}
}
Run Code Online (Sandbox Code Playgroud)
这是一种正确的前进方式,还是会导致性能问题?
最好的,马库斯
是否有一种优雅的方法来指定子程序参数的默认值?
目前,我使用以下方法:
use strict;
use warnings;
func1( "arg1", "arg2", opt1 => "first option", opt2 => 0 );
sub func1 {
my ( $arg1, $arg2, %opt ) = @_;
$opt{opt1} //= "no option";
$opt{opt2} //= 1;
$opt{opt3} //= [];
}
Run Code Online (Sandbox Code Playgroud)
当有很多选择时,它看起来有点难看.我宁愿这样做
sub func2 {
my ( $arg1, $arg2, $opt ) = process_args(
opt1 => "no option", opt2 => 1, opt3 => []
);
}
Run Code Online (Sandbox Code Playgroud)
我能想出的最好的方法是:
sub func2 {
my ( $arg1, $arg2, $opt ) = process_args(
\@_, 2, opt1 => "no …Run Code Online (Sandbox Code Playgroud)