Front page | perl.perl6.language |
Postings from July 2006
sprintf for S29
From:
Aaron Sherman
Date:
July 6, 2006 08:59
Subject:
sprintf for S29
Message ID:
1152201545.28796.249.camel@pps
I've taken a stab at sprintf for S29. All I've done differently from
Perl 5 is to drop %p and %n (generates an exception) and add %C
(closure) to replace the functionality of %n. Are there any additional
formats that we want to add?
Other than that, this should be exactly the same as Perl 5:
=item sprintf
our method Str Str::sprintf ( Str $format: *@args )
our multi Str sprintf ( Str $format, *@args )
This function is mostly identical to the C library sprintf function.
The C<$format> is scanned for C<%> characters. Any C<%> introduces a
format token. Format tokens have the following grammar:
grammar Str::SprintfFormat {
rule format_token { \%: <index>? <precision>? <modifier>? <directive> }
rule index { \d+ \$ }
rule precision { <flags>? <vector>? <precision_count> }
rule flags { <[\ +0\#\-]>+ }
rule precision_count { [ <[1-9]>\d* | \* ]? [ \. [ \d* | \* ] ]? }
rule vector { \*? v }
rule modifier { <[lhVqL]> | ll }
rule directive { <[\%csduoxefgXEGbpniDUOF]> }
}
Directives guide the use (if any) of the arguments. When a directive
(other than C<%>) are used, they indicate how the next argument
passed is to be formatted into the string.
The directives are:
% a percent sign
c a character with the given number
s a string
d a signed integer, in decimal
u an unsigned integer, in decimal
o an unsigned integer, in octal
x an unsigned integer, in hexadecimal
e a floating-point number, in scientific notation
f a floating-point number, in fixed decimal notation
g a floating-point number, in %e or %f notation
X like x, but using upper-case letters
E like e, but using an upper-case "E"
G like g, but with an upper-case "E" (if applicable)
b an unsigned integer, in binary
C special: invokes the arg as code, see below
Compatibility:
i a synonym for %d
D a synonym for %ld
U a synonym for %lu
O a synonym for %lo
F a synonym for %f
Perl 5 compatibility:
n produces a runtime exception (see below)
p produces a runtime exception
The special format directive, C<%C> invokes the target argument as
code, passing it the result string that has been generated thus
far and the argument array.
Here's an example of its use:
sprintf "%d%C is %d digits long",
$num,
sub($s,@args is rw) {@args[2]=$s.size},
0;
The special directive, C<%n> does not work in Perl 6 because of the
difference in parameter passing conventions, but the example above
simulates its effect using C<%C>.
=cut
--
Aaron Sherman <ajs@ajs.com>
Senior Systems Engineer and Toolsmith
"We had some good machines, but they don't work no more." -Shriekback
-
sprintf for S29
by Aaron Sherman