Re: Help! Strings -> Numbers
[email protected] (Michael Lazzaro) Wed, 20 Nov 2002 14:46:22 -0800
| Newsgroups | perl.perl6.documentation |
|---|---|
| Message-ID | <[email protected]> |
On Wednesday, November 20, 2002, at 01:45 PM, Tanton Gibbs wrote:
>>> my int $i is formatted('%4x');
>>> $i = 255;
>>> print $i; # prints '00ff';
>>
>> I too don't see much use in the former. The latter puts distance
>> between the formatting and the thing being formatted and that can't
>> be good.
>
> In situations such as these where you want a variable printed in a
> special way, wouldn't it be better to use printf? Isn't that what it
> was designed for?
Indeed, if we can't find anything significantly shorter or more obvious
than scanf/printf, we should drop it and just use those. For the
general case, it's unlikely we _will_ find anything.
I'd certainly like a way to easily (1) treat a string as bin/oct/hex,
and (2) stringify a number to bin/oct/hex, because those are two pretty
common cases. I've tried tons of things to get a more general syntax,
and nothing is really working. The string interpolation case is the
most infuriating, because it feels like something that should be easier
than it currently is:
using properties?
my int $i is formatted('%4x') = 255;
my int $i is hex = 255;
my int $i = 255 but formatted('%4x');
my int $i = 255 but hex;
named unary op?
my str $s = hex 0xff; # 'ff'
my str $s = hex:2 0xff; # 'ff'
my str $s = hex:4 0xff; # '00ff'
string interpolation? (where we need it most!)
"\$i is $(sprintf('%04x',$i))"
"\$i is $($i but formatted('%4x') )"
"\$i is $($i but hex)"
"\$i is $(hex $i)"
"\$i is <hex:$i>" # a rule-like shorthand for named formats?
Don't know, but I'm not seeing a good solution... This is one of the
things Perl4/5 "formats" were meant to help address, but those seem to
have fallen into disuse.
MikeL