Wednesday, September 29, 2010

Integer compare with ''

There is a tricky bug if you compare a number with empty string and if the number = 0:
                                                                                                    
#!/usr/bin/perl
#use warnings;
use strict;

my $v;

undef $v;

if (!defined($v)) {
print "Oops! \$v is not defined\n";
}

$v = 0;

if ($v == '') {
print "Oops! \$v == \'\'\n";
}

__END__

Result:
Oops! $v is not defined
Oops! $v == ''


You can see that if $v = 0, the condition:

$v == ''

will get TRUE!

Of course if you turn on warnings, you will not ignore this bug because compiler will give you this:

Argument "" isn't numeric in numeric eq (==) at ...

No comments:

Post a Comment