Help! Strings -> Numbers

[email protected] (Michael Lazzaro) Tue, 19 Nov 2002 10:59:02 -0800
Newsgroups perl.perl6.documentation
Message-ID <[email protected]>
OK, back to this, so we can finish it up: we have a number of proposals 
& questions re: string-to-num conversions, and from Luke we have some 
initial docs for them that need completing.  Can I get more feedback on 
these issues, plz, and any other String -> Number proposals/questions?


(A) Unification of Literal <--> Stringified Numeric Behaviors

An old proposal that I can't find anymore suggested that strings should 
be converted to a number according to the exact same rules as literals, 
such that:

     0123   == "0123"
     0xff   == "0xff"
     20#1gj == "20#1gj"
     1e10   == "1e10"

.... in the interest of regularity, flexibility, etc.  Comments?


(B) We want to be able to convert strings to numbers, using strings in 
any of the formats that literals understand.  If (A) is accepted, this 
is unnecessary: if not, we need a conversion syntax, maybe something 
like one of:

     my $s = "20#1gj";

     my num $i = literal $s;   # (1a) literal is a func or unary op
     my num $i = numeric $s;   # (1b) alternate spelling?
     my num $i = $s.literal;   # (2a) str has method 'literal'
     my num $i = $s.numeric;   # (2b)


(C) We sometimes want to be able to specify the _exact_ format a string 
should be expected as.  Suppose you wanted a user to always enter a hex 
value: they should be able to just enter "10" or "ff", and you wanted 
to convert that to 16 and 255, respectively.  So you'd maybe use 
something like:

     my $s = "ff";        # note there's no '0x' in front

     my int $i = hex $s;
     my int $i = $s.hex;
     my int $i = $s.numeric('%2x');  # ???

e.g. is "numeric" a method of str, and if so, can it accept formatting 
information?  And are there shortcuts for the common cases that 
literals already know about, e.g. <<sci dec bin oct hex>>?


(D) There were proposals to allow a given string to _always_ be 
numified in a certain way by attaching a property, e.g.:

     my str $s is formatted('%2x');
     $s = 'ff';
     my int $i = $s;  # 255

....now I'm wondering if that's buying us anything, though the inverse 
seems much more useful:

     my int $i is formatted('%4x');
     $i = 255;
     print $i;    # prints '00ff';

Anyone care to comment?  Compiletime property, runtime property, or 
both?


(E) We need to finalize what happens when a string isn't a number, or 
has additional trailing stuff.  Damian gave his initial preference, but 
we need to verify & set in stone:

     my int $i =  'foo';   # 0, NaN, undef, or exception?
     my int $i = '5foo';   # 5, NaN, undef, or exception?

     my Int $i =  'foo';   # 'Int' probably makes a difference
     my Int $i = '5foo';


MikeL