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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.