简体   繁体   English

在Perl中使用defined / undef

[英]Use of defined/undef in Perl

I am planning to pass two variables to a perl function, one of which may be optional. 我打算将两个变量传递给perl函数,其中一个可能是可选的。 I am trying to check if the second one is defined or not, but it doesn't work correctly. 我试图检查第二个是否已定义,但它无法正常工作。 When I called the function as myFunction(18), it assumes that the variable $optional is defined and goes to the else statement. 当我将函数调用为myFunction(18)时,它假定变量$ optional已定义并转到else语句。 But in the else statement when the $optional variable is being accessed it throws an "uninitialized" error. 但是在else语句中,当访问$ optional变量时,它会抛出“未初始化”错误。 This is exactly opposite of what I have expected. 这与我的预期完全相反。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

sub myFunction {
  my ($length, $optional) = (@_);
  if(undef($optional)
  {
    more code..
  }
  else
  {
    more code...
  }
}

myFunction(18)

The correct function is defined . defined正确的功能。 undef undefines $optional . undef定义$optional What you want to do is something like this: 你想要做的是这样的:

sub myFunction {
    my( $length, $optional ) = @_;
    if( ! defined $optional ) {
        # Do whatever needs to be done if $optional isn't defined.
    }
    else {
        # Do whatever can be done if $optional *is* defined.
    }
}

Another way to deal with it (especially Perl 5.10+) is to use the "defined or" operator, // , like this: 另一种处理它的方法(特别是Perl 5.10+)是使用“defined or”运算符// ,如下所示:

sub MyFunc {
    my $length = shift;
    my $optional = shift // 'Default Value';
    # Do your stuff here.
}

What that does is detect whether the return value of shift @_ is defined. 这样做是检测是否定义了shift @_的返回值。 Since you already called shift once, we're now testing the second parameter. 由于您已经调用了一次shift,我们现在正在测试第二个参数。 If it's defined, assign the value to $optional . 如果已定义,请将值指定给$optional If it's not defined, assign 'Default Value' to $optional . 如果未定义,请将'Default Value'指定给$optional Of course you have to come up with your own sane default. 当然,你必须提出自己的理智默认值。

If you're stuck in the dark ages of pre-Perl 5.10, you could accomplish the same with: 如果你陷入了Perl 5.10之前的黑暗时代,你可以用以下方法完成同样的事情:

my $optional = shift;
$optional = defined $optional ? $optional : 'Default value';

...or... ...要么...

my $length = shift;
my $optional = defined( $_[0] ) ? shift : 'Default value';

Either way, I often prefer having a sane default, rather than a totally separate control flow path. 无论哪种方式,我通常更喜欢具有理智的默认值,而不是完全独立的控制流路径。 It's often a good way to simplify code. 这通常是简化代码的好方法。

my $optional = defined( $_[0] ) ? shift : 'Default value';

这是危险的代码,因为它只会在定义时移动参数,如果你有第三个参数,这会在你打电话时变得混乱

MyFunc( 10, undef, 20 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM