3

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?

1
  • Read documentation for defined -- change your code to elsif( ! defined($arrTest[1]) ) { Commented Jun 4, 2022 at 5:57

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Every Perl script should have use strict; and use warnings; as the first two lines. The only acceptable situation to omit those is when working with extremely legacy code that doesn't follow strict guidelines.
@SilvioMayolo Yes, thank you, and I never get tired of posting that ... still editing and will work in that strict as well (which has nothing to do with this question so it's not clear how best to weave it in)
Can I ask one more question? How can I distinguish if an array is empty?
@blueFish "distinguish if an array is empty?" -- For that we can simply test for truth, if (@ary) (it has something), or if (not @ary) (empty). Note that if (@ary) is true even if the array has an element which is undef or an empty string. It tests whether there is anything in it
@blueFish "Can I ask one more question?" -- yes please, all you need :) I hope that this post answered your original question (as posted) but please ask whatever else needs clarification. (I'll let you know if I feel that you'd better ask a separate question, or if it just can't be answered in a skinny comment, etc)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.