我试图找出在 Perl 中区分未传递参数和参数已作为 0 传递的情况的最佳方法,因为它们对我来说意味着不同的事情。
(通常我喜欢这种歧义,但在本例中我生成 SQL,因此我想用 NULL 替换未定义的参数,但将 0 保留为 0。)
所以这就是歧义:
sub mysub {
my $arg1 = shift;
if ($arg1){
print "arg1 could have been 0 or it could have not been passed.";
}
}
到目前为止,这是我最好的解决方案......但我认为它有点丑陋。我想知道您是否可以想出一种更干净的方法,或者这对您来说是否可行:
sub mysub {
my $arg1 = (defined shift) || "NULL";
if ($arg1 ne "NULL"){
print "arg1 came in as a defined value.";
}
else {
print "arg1 came in as an undefined value (or we were passed the string 'NULL')";
}
}
以下是如何处理所有可能情况的示例:
sub mysub {
my ($arg1) = @_;
if (@_ < 1) {
print "arg1 wasn't passed at all.\n";
} elsif (!defined $arg1) {
print "arg1 was passed as undef.\n";
} elsif (!$arg1) {
print "arg1 was passed as a defined but false value (empty string or 0)\n";
} else {
print "arg1 is a defined, non-false value: $arg1\n";
}
}
(@_
是函数的参数数组。将其与1
这里是计算数组中元素的数量。我刻意回避shift
,因为它改变了@_
,这需要我们存储原始大小@_
某处。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)