我有一个带有这样原型(prototype)的子程序:
sub printFoo(%) {
my (%hashFoo)=@_;
# do stuff with the hash
}
但我想有选择地传入第二个标量参数,如下所示:
sub printFoo(%;$) {
my (%hashFoo,$optionalArg)=@_;
# do stuff with the hash and the optional arg
}
我知道在警告模式下这是一个禁忌,但我不知道为什么。
我想我可以使用全局变量标志,但是关于如何优雅地完成这种类型的函数签名有什么建议吗?
最佳答案
我不知道这算不算优雅,但是...
sub printFoo {
my $optionalArg;
if (@_ % 2 != 0) {
$optionalArg = pop @_;
}
my %hashFoo = @_;
...
}
带有哈希引用的原型(prototype)也可以工作。您仍然会使用散列调用该函数,但您必须记住第一个散列 arg 将被您的子作为散列引用接收。
sub printFoo (\%;$) { # call as printFoo %foo or printFoo %foo, 42
my ($hashFooRef, $optionalArg) = @_;
my %hashFoo = %$hashFooRef;
...
}
关于perl - 带有散列和可选标量参数的子例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32399603/