Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: undef element in array

Tags:

perl

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?

like image 739
blueFish Avatar asked Jun 09 '26 19:06

blueFish


1 Answers

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.

like image 93
zdim Avatar answered Jun 12 '26 11:06

zdim