blueFish
blueFish

Reputation: 79

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". But it prints "one" here...

Does it mean $arrTest[1]=undef=0?

How can I modify the "if condition" to distinguish the "undef" in array element?

Upvotes: 3

Views: 197

Answers (1)

zdim
zdim

Reputation: 66964

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

Most of the time when this need be done we get to hear about it (there are some exceptions) -- if we have 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. 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.

Upvotes: 7

Related Questions