String to Num (was Re: Numeric Literals (Summary))
[email protected] (Michael Lazzaro) Fri, 15 Nov 2002 12:16:55 -0800
| Newsgroups | perl.perl6.documentation |
|---|---|
| Message-ID | <[email protected]> |
Let's summarize some of the string-to-num issues:
(1) -- A number is just a number, regardless of how it's put in.
Therefore:
my int $i = 0xff;
my int $i = 255;
result in the identical number, 255, being placed in $i. Once it's in
there, there's no way to tell what format it originally came in,
because we don't care.
(2) -- We want to be able to parse a string as a number using all the
same rules that Perl uses. This implies there is a function, perhaps
C<literal> or similar, that allows this:
my int $i = literal "0xff"; # 255
(3) -- We want to be able to parse a string as a number using a very
_specific_ rule; for example, if a user is expected to enter a value in
a specific format, like octal "755" or hex "FF", we want to "know" what
we're expecting. That implies there may be functions for each common
format:
my int $i = sci "1e33";
my int $i = hex "00ff";
(4) -- We want to be able to output numbers to strings according to
specific formatting rules. One way to do this (aside from using
sprintf) is to use sprintf-style formatting strings, perhaps as
properties to tie them to individual instances:
my int $i = literal "0xff" but as_string('%02x');
or explicitly each time you call the stringifyier:
my str $s = str($i : base => 16 );
my str $s = str($i : format => '%02x');
or explicitly by using a class method of the number to force it:
my str $s = $i.as_string('%02x');
(5) -- An earlier proposal I had is to make C<bin>, C<oct>, C<hex>,
etc. subclasses that overloaded their string-in and string-out methods,
such that:
my sci $i = "1e5" # 10**5
my hex $i = "ff"; # 255
print $i; # "FF"
print bin $i; # "11111111"
which is very useful for some scripts, and would give the typecasts
shown in (3) and (4) for free. If you wanted to do the same for any
arbitrary format, you'd have to make your own classes with similar
string in/out rules.
Comments?
MikeL