int 'comparison operator' int # returns the actual result
int 'comparison operator' string # returns an error
Should
(5 == '5') (which is "int 'comparison operator' string") return the result ? Or should it throw an error ? Assuming it should return the result, the following may help:
use warnings;
# Write the warnings handler. It only handles runtime errors.
# To have it handle compile-time errors, place it in a
# BEGIN{} block
$SIG{__WARN__} = sub {
for my $w (@_) {
if($w =~ /isn't numeric/) {die "Treated a string as a number"}
else {print "Warning received: $w"}
}
};
# Generates a compile-time warning ("...used only once...")
# that the handler doesn't deal with.
$foo = 0;
#Generates a runtime warning ("... uninitialized value ...")
# that the handler *does* deal with.
my $bar;
print $bar, "\n";
$int = 7;
$string = '5foo';
if($int == 7) {print "Yep, \$int == 7\n"}
# Generates a warning that causes the handler to throw
# the error
if($string == 5) {print "Yep, \$string == 5\n"}
Note, however, that
any treatment of $string as a number (eg
$string += 3;) will cause the handler sub to throw the error.
Perhaps all you really need is
Scalar::Util::looks_like_number() (see 'perldoc Scalar::Util').
use Scalar::Util;
.
.
if(Scalar::Util::looks_like_number($x) &&
$x > 0) {
print "It's a positive number - not necessarily an integer";
}
Maybe even:
use Scalar::Util;
.
.
if(Scalar::Util::looks_like_number($x) &&
$x > 0 && $x == int($x)) {
print "It's a positive integer";
}
But that can be a little dubious, too:
use Scalar::Util;
use warnings;
$string = '5.' . '0' x 30 . '1';;
print $string, "\n";
if(Scalar::Util::looks_like_number($string) &&
$string > 0 && $string == int($string) ) {
print "looks like a positive integer\n";
}
else {print "not a positive integer\n"}
__END__
Outputs:
5.0000000000000000000000000000001
looks like a positive integer
That probably does the right thing imo, but I wouldn't like to guarantee that everyone would agree.
Cheers,
Rob