简体   繁体   English

Perl:数组中的 undef 元素

[英]Perl: undef element in array

I defined some elements in an array:我在数组中定义了一些元素:

my @arrTest;
$arrTest[0]=1;
$arrTest[2]=2;

#Result for @arrTest is: (1, undef, 2)


if($arrTest[1]==0)
{
    print "one\n";
}
elsif($arrTest[1] == undef)
{
    print "undef\n";
}

I think it should print "undef".我认为它应该打印“undef”。 But it prints "one" here...但它在这里打印“一个”......

Does it mean $arrTest[1]=undef=0?这是否意味着 $arrTest[1]=undef=0?

How can I modify the "if condition" to distinguish the "undef" in array element?如何修改“if 条件”以区分数组元素中的“undef”?

The operator == in the code $arrTest[1] == 0 puts $arrTest[1] in numeric context and so its value gets converted to a number if needed, as best as the interpreter can do, and that is used in the comparison.代码$arrTest[1] == 0中的运算符==$arrTest[1]放在数字上下文中,因此如果需要,它的值将被转换为数字,尽解释器所能做的,并且在比较。 And when a variable in a numeric test hasn't been defined a 0 is used so the test evaluates to true (the variable stays undef ).并且当尚未定义数字测试中的变量时,使用0以便测试评估为真(变量保持undef )。

Most of the time when this need be done we get to hear about it (there are some exceptions) -- if we have use warnings;大多数时候,当我们需要这样做时,我们会听到它(有一些例外)——如果我们有use warnings; that is (best at the beginning of the program) Please always have warnings on, and use strict .那是(最好在程序开始时) 请始终打开警告,并使用严格 They directly help.他们直接提供帮助。

To test for defined-ness there is defined为了测试定义性,定义

if (not defined $arrTest[1]) { ... }

A demo 演示

perl -wE'say "zero" if $v == 0; say $v; ++$v; say $v'

The -w enables warnings. -w启用警告。 This command-line program prints这个命令行程序打印

Use of uninitialized value $v in numeric eq (==) at -e line 1.
zero
Use of uninitialized value $v in say at -e line 1.

1

Note how ++ doesn't warn, one of the mentioned exceptions.请注意++如何不发出警告,这是提到的例外之一。

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

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