我试图找出最好的区分Perl的最佳方法,在这种情况下,没有传递参数的情况和传递参数为0的情况之间的区别,因为它们对我而言意味着不同的含义。
(通常,我喜欢模棱两可,但是在这种情况下,我正在生成SQL,因此我想用NULL替换未定义的args,但将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
,因为它会更改@_
,这将需要我们将@_
的原始大小存储在某个位置)
关于perl - 如何区分未传递的参数和传递错误值的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8299662/