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

前端之家收集整理的这篇文章主要介绍了perl – 如何区分未传递的参数和使用false值传递的参数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图找出在没有传递参数的情况和参数传递为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.";
  }
}

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

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进行比较是计算数组中元素的数量.我故意避免移位,因为它改变了@_,这将要求我们存储原始大小@_某处.)

原文链接:https://www.f2er.com/Perl/172377.html

猜你在找的Perl相关文章