Here's the very rough draft of the String <=> Num document I said I'd
Some of the behavior in here was just what made sense to me, since I
had no definitive answer. If anyone has ideas for more useful
or sensible behavior, please say so.
Oh, and I'm not sure what POD-like conventions we're using, so please
correct me on that too.
=section ## Converting between numbers and strings
Numbers can be displayed in many different ways. This section covers
how you can represent a number as a string, or vice versa, precisely
how you want.
=section ### Converting numbers to strings
The most straightforward way to convert a number to a string is simply
to use it as one.
my $num = 3.14;
$num ~= 'foo'; # $num contains '3.14foo'
The number is converted to string form in the shortest, correctly
rounded way that results in the same number if converted back. This
means that integers will print all their digits, and floating point
numbers won't resort to scientific notation until there are enough
zeroes to make scientific notation shorter.
To get finer-grained control over how your numbers are represented as
strings or printed, use the C<printf> or C<sprintf> functions.
Should I document printf and sprintf here?
Is there an C<is formatted> property or something like that, which
would be like an Awk OFMT on a per-variable basis?
=section ### Converting strings to numbers
Just as numbers can be used as strings, strings will automatically
convert themselves to numbers. By default, this is done by taking all
the numbers starting at the beginning of the string, discarding
leading whitespace, up until the first non-numeric character (treating
the decimal point and exponential notation as numeric characters). If
the string is not entirely numeric and C<warnings> are enabled, a
warning is issued.
my ($x, $y, $z) = ≪12.6pi 0x3f 6.022e22≫
$x += 1; # 13.6 with warning ("pi" not numeric)
my $w = $y - 1; # $w = -1 with warning ("x3f" not numeric)
$z /= 2; # 3.011e22 and no warning
To extract a number specified in any notation that Perl allows, and
check whether it is a well-formed Perl number, use the C<.numeric>
The C<.numeric> method on strings returns the number contained in the
string, even if it's in arbitrary base notation, dotted notation, or
anything else Perl understands. It C<fail>s if the string is not a
well-formed number. Leading and trailing whitespace is ignored.
'6124872'.numeric; # 6124872
'3.2e6'.numeric; # 3200000
'0c27'.numeric; # 23
'34foo'.numeric; # fail (undef/exception)
'16:3D'.numeric; # 61
'8:3D'.numeric; # fail