我试图找出在 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')";
}
}