如何区分未通过的参数和使用false值传递的参数?

Ste*_*hen 8 perl arguments undefined shift subroutine

我试图找出在没有传递参数的情况和参数传递为0的情况下在Perl中区分的最佳方法,因为它们对我来说意味着不同的东西.

(通常我喜欢歧义,但在这种情况下我生成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.";
  }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我最好的解决方案......但我认为这有点难看.我想知道你是否可以想到一个更清洁的方式或者这对你来说是否合适:

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')";
  }
}
Run Code Online (Sandbox Code Playgroud)

dus*_*uff 16

以下是如何处理所有可能情况的示例:

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

(@_是函数的参数数组.将它与1此处进行比较是计算数组中元素的数量.我故意避免shift,因为它会改变@_,这将要求我们存储@_某个地方的原始大小.)