In my perl script, I used if ($a == undef)
condition, I thought it is the same as if (not defined $a)
, where $a
is a string as read from a csv file. However, I noticed that several string values ("", " ", "0", "-0", "+0", "@", "a"
, and many other spaces and special characters) are defined but also undef
. If undef
is only for numeric values, it should pass "0"
, "+0"
, and "-0"
. Can anyone explain? I understand now that I should not use if ($a == undef)
to replace if (not defined $a)
.
My testing code is:
@a_array = ("-1", "-0", "0", "+0", "1", "", " ", "@", "a", "\$", "-");
undef $a;
test_a();
foreach $a (@a_array) {
$len_a = length($a);
test_a();
}
sub test_a {
if (defined $a) { print "a = $a is defined; "} else {print "a = $a not defined; "};
if ($a == undef) { print "a = $a (== undef); "} else {print "a = $a (!= undef); "};
if (length($a) > 0){ print "length of a is $len_a > 0 \n"} else {print "length of a is $len_a !> 0 \n"};
}