Subject: | Is it really that difficult to tell the difference between undef and 0?? |
The pod claims, "The number zero and undef are difficult to determine
in Perl", but it doesn't seem that difficult to me...
my $var1 = 0;
my $var2 = undef;
print "\$var1 is zero\n" if $var1 eq 0;
print "\$var2 is zero\n" if $var2 eq 0;
print "\$var1 is undef\n" if !defined $var1;
print "\$var2 is undef\n" if !defined $var2;
Of course, I suppose this depends on how you define zero. Does "0.0"
count as zero? How about the string "0E0" or the string "0 but true"?
Anyway, here are some interesting results where Number::Zero gets
things wrong....
use 5.010;
use strict;
use warnings;
use Number::Zero;
{
package FalseNumber;
use overload
q[bool] => sub { '' },
q[0+] => sub { $_[0][0] },
fallback => 1,
;
}
{
package TrueNumber;
use overload
q[bool] => sub { 't' },
q[0+] => sub { $_[0][0] },
fallback => 1,
;
}
sub test {
my $maybe_zero = shift;
say "This number is: $maybe_zero";
say "This number plus one is: ", $maybe_zero + 1;
say "Number::Zero thinks this number... ",
Number::Zero::is_zero($maybe_zero) ? "is zero" : "is
not zero";
}
test(
bless [123] => 'FalseNumber'
);
test(
bless [0] => 'TrueNumber'
);