perl - 如何区分未传递的参数和传递错误值的参数?

标签 perl arguments undefined shift subroutine

我试图找出最好的区分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/

相关文章:

perl - 日志文件两行之间的时间差

regex - 如何在 Perl 中使用正则表达式检查字符串是否符合精确模式

windows - 突然之间,perl 脚本不起作用,除非我在它们前面加上 "perl"并提供脚本的完整路径

c++ - 从 C++ 调用 Lua 函数,缺少参数

php - 尝试连接到其他文件中的数据库时无法使用常量

JavaScript:在方法中使用对象变量

javascript - 无需多次中间检查即可获取嵌套的 JSON/对象值?

perl - NET::LDAP 过滤器,带有 OR

c - 如何用我定义的错误消息替换 Linux 内核错误消息?

c - 如何正确编写参数函数?