Probably because Perl doesn't differentiate internally between strings and numbers. So can I tell Perl it's a number?
Perl does know whether a variable is a string or a number. Normally this is of no consequence because Perl "does the right thing" (usually). You can tell Perl to explicitly convert a string to a number by simply doing some math on the variable! One use for this is to remove leading zeroes. $var="000123"; $var +=0; Now $var is 123 because it is flagged internally as numeric. Of course if $var is already being used as a numeric value, adding zero to it is harmless.
Update: More fun with strings...Occasionally seen when using the DB. Sometimes it is necessary to return essentially 2 values: a)the operation "worked" and b) the result is numeric zero.
use strict;
use warnings;
my $var = " 0123";
$var += 0;
print "$var\n";
$var = "0 but true";
$var += 0;
print "$var\n";
$var = "0E0";
$var += 0;
print "$var\n";
__END__
Prints:
123
0
0
The string "0 but true" is hardcoded into Perl as an exception. This is logically "true" but numerically 0.
If we had "zero but true", that throws a warning: "Argument "zero but true" isn't numeric in addition (+) at...", but you get numeric 0 anyway. |