我怎么可能用错误的值传递,这不是传递参数和一个区别? [英] How can I distinguish between an argument that was not passed and one that was passed with a false value?

查看:112
本文介绍了我怎么可能用错误的值传递,这不是传递参数和一个区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出在Perl,其中一个说法未获通过的情况下之间differeniate的最佳方式,并在参数已通过为0,因为它们意味着不同的东西给我。

(通常我喜欢的模糊性,但在这种情况下,我产生SQL,所以我想,以取代NULL未定义ARGS,但留下0 0。)

因此​​,这是模棱两可:

 子mysub {
  我的$ ARG1 =转变;
  如果($ ARG1){
    打印ARG1本来0或者它可能没有被通过。
  }
}

到目前为止,这是我最好的解决办法...但我认为这是一个有点难看。我想知道,如果你能想到的一个更清洁的方式,或者如果这看起来确定你:

 子mysub {
  我的$ ARG1 =(定义移)|| 空值;
  如果($ ARG1 NENULL){
    打印ARG1进来作为一个定义的值。
  }
  其他{
    打印ARG1进来作为一个未定义的值(或者我们传递的字符串'NULL');
  }
}


解决方案

下面是一个如何处理所有可能的情况下,一个例子:

 子mysub {
    我($ ARG1)= @_;
    如果(@_&所述; 1){
        打印ARG1完全没有通过\\ n;
    } ELSIF(!$定义ARG1){
        打印ARG1是为undef通过\\ n;
    } ELSIF(!$ ARG1){
        打印ARG1被作为一个定义,但假值传递(空字符串或0)\\ n;
    }其他{
        打印ARG1是一个定义,非假值:$ ARG1 \\ N的;
    }
}

@_ 是参数数组的功能。它相较于 1 这里计数数数组中的元素。我故意避开,因为它改变了 @_ ,这将要求我们存储的原始大小 @_ 的某个地方。)

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.

(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.)

So this is the ambiguity:

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

(@_ 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天全站免登陆