In Cool§

See primary documentation in context for method sprintf

method sprintf(*@args)

Returns a string according to a series of format directives that are common in many languages; the object will be the format string, while the supplied arguments will be what's going to be formatted according to it.

"% 6s".sprintf('Þor').say# OUTPUT: «   Þor␤» 

In Independent routines§

See primary documentation in context for routine sprintf

multi sub sprintf(Cool:D $format*@args)

Returns a string according to a format as described below. The format used is the invocant (if called in method form) or the first argument (if called as a routine).

sprintf"%s the %d%s""þor"1"st").put# OUTPUT: «þor the 1st␤» 
sprintf"%s is %s""þor""mighty").put;   # OUTPUT: «þor is mighty␤» 
"%s's weight is %.2f %s".sprintf"Mjölnir"3.3392"kg").put;
# OUTPUT: «Mjölnir's weight is 3.34 kg␤» 
# OUTPUT: «Mjölnir's weight is 3.34 kg␤»

This function is mostly identical to the C library's sprintf and printf functions. The only difference between the two functions is that sprintf returns a string while the printf function writes to a filehandle. sprintf returns a Str, not a literal.

The $format is scanned for % characters. Any % introduces a format token. Directives guide the use (if any) of the arguments. When a directive other than % is used, it indicates how the next argument passed is to be formatted into the string to be created. Parameter indexes may also be used in the format tokens. They take the form N$ and are explained in more detail below.

The $format may be defined enclosed in single or double quotes. The double-quoted $format string is interpolated before being scanned and any embedded string whose interpolated value contains a % character will cause an exception. For example:

my $prod = "Ab-%x-42";
my $cost = "30";
sprintf("Product $prod; cost: \$%d"$cost).put;
# OUTPUT: «Your printf-style directives specify 2 arguments, but 1 argument was supplied␤» 
          «  in block <unit> at <unknown file> line 1␤»

When handling unknown input you should avoid using such syntax by putting all variables in the *@args array and have one % for each in $format. If you need to include a $ symbol in the format string (even as a parameter index) either escape it or use the single-quoted form. For example, either of the following forms works without error:

sprintf("2 x \$20 = \$%d"2*20).put# OUTPUT: «2 x $20 = $40␤» 
sprintf('2 x $20 = $%d'2*20).put;   # OUTPUT: «2 x $20 = $40␤» 

In summary, unless you need something very special, you will have fewer unexpected problems by using the single-quoted format string and not using interpolated strings inside the format string.

[1]