如何区分未传递的参数和使用假值传递的参数? [英] How can I distinguish between an argument that was not passed and one that was passed with a false value?

查看:26
本文介绍了如何区分未传递的参数和使用假值传递的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出在 Perl 中区分参数未传递和参数已传递为 0 的最佳方法,因为它们对我来说意义不同.

I am trying to figure the best way to differeniate in Perl between cases where an argument has not been passed, and where an argument has been passed as 0, since they mean different things to me.

(通常我喜欢歧义,但在这种情况下我正在生成 SQL,所以我想用 NULL 替换未定义的参数,但将 0 保留为 0.)

(Normally I like the ambiguity, but in this case I'm generating SQL so I want to replace undefined args with NULL, but leave 0 as 0.)

所以这就是歧义:

sub mysub {
  my $arg1 = shift;
  if ($arg1){
    print "arg1 could have been 0 or it could have not been passed.";
  }
}

到目前为止,这是我最好的解决方案......但我认为它有点丑陋.我想知道您是否能想到一种更简洁的方法,或者这对您来说是否合适:

And so far, this is my best solution... but I think it is a little ugly. I'm wondering if you can think of a cleaner way or if this looks OK to you:

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')";
  }
}

推荐答案

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

Here's an example of how you can handle all the possible cases:

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,因为它改变了 @_,这需要我们将 @_ 的原始大小存储在某处.)

(@_ is the array of arguments to your function. Comparing it to 1 here is counting the number of elements in the array. I'm intentionally avoiding shift, as it alters @_, which would require us to store the original size of @_ somewhere.)

这篇关于如何区分未传递的参数和使用假值传递的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆