Re: Help! Strings -> Numbers
[email protected] (Michael Lazzaro) Thu, 21 Nov 2002 11:16:02 -0800
| Newsgroups | perl.perl6.documentation |
|---|---|
| Message-ID | <[email protected]> |
On Thursday, November 21, 2002, at 12:16 AM, Dave Storrs wrote:
> I do agree that having it be a method (and hence overloadable) is the
> best solution. I just wish there were some way to get away from those
> dratted sprintf format strings.
Amen. God, I've hated those things for years. And yet most attempts I
make at something just as powerful begins to look an awful lot like it
anyway.
I keep musing over possible scenarios, two in particular:
1) "Formats" as classes. What I _want_ to do is to be able to
associate a named "format" with a given class/instance/output, because
I tend to use the same few formats over and over. So if I want to
frequently output numbers as '%-4.2d', I just call it "MoneyFormat" or
something:
class MoneyFormat is NumFormat {
sub width { 4 };
sub precision { 2 };
sub align { 'right' };
}
And then later I can say things like:
print $v.as(MoneyFormat); # just pass the class name
print $v.as(MoneyFormat.new); # or a specific instance
and not deal with sprintf syntax at all, but still have something
that's eminently adjustable, self-documenting, and has decent
compile-time optimization possibilities. And could change, runtime,
according to user preferences.
2) An analogue to a "rule", but for output instead of input. As we can
say:
$s ~~ /<number>/
if we've defined a rule called <number>, it feels like it would be
useful to allow similar "output rules" that format things for
interpolation. Like:
print "blah blah: <$i:MoneyFormat>";
But that would mean you couldn't use literal < > in interpolated
strings, which might be a pain in todays XML-centric world. I like the
general "output rule" idea a lot, though, because it represents how you
typically use formatting -- inside a larger interpolation.
It would be very useful in the second half of a s///, too (grab a
match, rewrite it in a canonical form):
$s ~~ s/<number>/<number:MoneyFormat>/;
Or something like that. I know I'm stream-of-conciousnessing here, it
just feels like we're missing something...
MikeL