sprintf - Perldoc Browser (original) (raw)
Returns a string formatted by the usual printf
conventions of the C library function sprintf
. See below for more details and see sprintf(3) or printf(3) on your system for an explanation of the general principles.
Perl does its own sprintf
formatting: it emulates the C function sprintf(3), but doesn't use it except for floating-point numbers, and even then only standard modifiers are allowed. Non-standard extensions in your local sprintf(3) are therefore unavailable from Perl.
Unlike printf
, sprintf
does not do what you probably mean when you pass it an array as your first argument. The array is given scalar context, and instead of using the 0th element of the array as the format, Perl will use the count of elements in the array as the format, which is almost never useful.
Note that the number of exponent digits in the scientific notation produced by %e
, %E
, %g
and %G
for numbers with the modulus of the exponent less than 100 is system-dependent: it may be three or less (zero-padded as necessary). In other words, 1.23 times ten to the 99th may be either "1.23e99" or "1.23e099". Similarly for %a
and %A
: the exponent or the hexadecimal digits may float: especially the "long doubles" Perl configuration option may cause surprises.
Between the %
and the format letter, you may specify several additional attributes controlling the interpretation of the format. In order, these are:
#format parameter index
An explicit format parameter index, such as 2$
. By default sprintf will format the next unused argument in the list, but this allows you to take the arguments out of order:
printf '%2$d %1$d', 12, 34; # prints "34 12"
printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1"
#flags
one or more of:
space prefix non-negative number with a space
+ prefix non-negative number with a plus sign
- left-justify within the field
0 use zeros, not spaces, to right-justify
# ensure the leading "0" for any octal,
prefix non-zero hexadecimal with "0x" or "0X",
prefix non-zero binary with "0b" or "0B"
For example:
printf '<% d>', 12; # prints "< 12>"
printf '<% d>', 0; # prints "< 0>"
printf '<% d>', -12; # prints "<-12>"
printf '<%+d>', 12; # prints "<+12>"
printf '<%+d>', 0; # prints "<+0>"
printf '<%+d>', -12; # prints "<-12>"
printf '<%6s>', 12; # prints "< 12>"
printf '<%-6s>', 12; # prints "<12 >"
printf '<%06s>', 12; # prints "<000012>"
printf '<%#o>', 12; # prints "<014>"
printf '<%#x>', 12; # prints "<0xc>"
printf '<%#X>', 12; # prints "<0XC>"
printf '<%#b>', 12; # prints "<0b1100>"
printf '<%#B>', 12; # prints "<0B1100>"
When a space and a plus sign are given as the flags at once, the space is ignored.
printf '<%+ d>', 12; # prints "<+12>"
printf '<% +d>', 12; # prints "<+12>"
When the # flag and a precision are given in the %o conversion, the precision is incremented if it's necessary for the leading "0".
printf '<%#.5o>', 012; # prints "<00012>"
printf '<%#.5o>', 012345; # prints "<012345>"
printf '<%#.0o>', 0; # prints "<0>"
#vector flag
This flag tells Perl to interpret the supplied string as a vector of integers, one for each character in the string. Perl applies the format to each integer in turn, then joins the resulting strings with a separator (a dot .
by default). This can be useful for displaying ordinal values of characters in arbitrary strings:
printf "%vd", "AB\x{100}"; # prints "65.66.256"
printf "version is v%vd\n", $^V; # Perl's version
Put an asterisk *
before the v
to override the string to use to separate the numbers:
printf "address is %*vX\n", ":", $addr; # IPv6 address
printf "bits are %0*v8b\n", " ", $bits; # random bitstring
You can also explicitly specify the argument number to use for the join string using something like *2$v
; for example:
printf '%*4$vX %*4$vX %*4$vX', # 3 IPv6 addresses
@addr[1..3], ":";
#(minimum) width
Arguments are usually formatted to be only as wide as required to display the given value. You can override the width by putting a number here, or get the width from the next argument (with *
) or from a specified argument (e.g., with *2$
):
printf "<%s>", "a"; # prints "<a>"
printf "<%6s>", "a"; # prints "< a>"
printf "<%*s>", 6, "a"; # prints "< a>"
printf '<%*2$s>', "a", 6; # prints "< a>"
printf "<%2s>", "long"; # prints "<long>" (does not truncate)
If a field width obtained through *
is negative, it has the same effect as the -
flag: left-justification.
#precision, or maximum width
You can specify a precision (for numeric conversions) or a maximum width (for string conversions) by specifying a .
followed by a number. For floating-point formats except g
and G
, this specifies how many places right of the decimal point to show (the default being 6). For example:
# these examples are subject to system-specific variation
printf '<%f>', 1; # prints "<1.000000>"
printf '<%.1f>', 1; # prints "<1.0>"
printf '<%.0f>', 1; # prints "<1>"
printf '<%07.2f>', 1.3; # prints "<0001.30>"
printf '<%e>', 10; # prints "<1.000000e+01>"
printf '<%.1e>', 10; # prints "<1.0e+01>"
For "g" and "G", this specifies the maximum number of significant digits to show; for example:
# These examples are subject to system-specific variation.
printf '<%g>', 1; # prints "<1>"
printf '<%.10g>', 1; # prints "<1>"
printf '<%g>', 100; # prints "<100>"
printf '<%.1g>', 100; # prints "<1e+02>"
printf '<%.2g>', 100.01; # prints "<1e+02>"
printf '<%.5g>', 100.01; # prints "<100.01>"
printf '<%.4g>', 100.01; # prints "<100>"
printf '<%.1g>', 0.0111; # prints "<0.01>"
printf '<%.2g>', 0.0111; # prints "<0.011>"
printf '<%.3g>', 0.0111; # prints "<0.0111>"
For integer conversions, specifying a precision implies that the output of the number itself should be zero-padded to this width, where the 0 flag is ignored:
printf '<%.6d>', 1; # prints "<000001>"
printf '<%+.6d>', 1; # prints "<+000001>"
printf '<%-10.6d>', 1; # prints "<000001 >"
printf '<%10.6d>', 1; # prints "< 000001>"
printf '<%010.6d>', 1; # prints "< 000001>"
printf '<%+10.6d>', 1; # prints "< +000001>"
printf '<%.6x>', 1; # prints "<000001>"
printf '<%#.6x>', 1; # prints "<0x000001>"
printf '<%-10.6x>', 1; # prints "<000001 >"
printf '<%10.6x>', 1; # prints "< 000001>"
printf '<%010.6x>', 1; # prints "< 000001>"
printf '<%#10.6x>', 1; # prints "< 0x000001>"
For string conversions, specifying a precision truncates the string to fit the specified width:
printf '<%.5s>', "truncated"; # prints "<trunc>"
printf '<%10.5s>', "truncated"; # prints "< trunc>"
You can also get the precision from the next argument using .*
, or from a specified argument (e.g., with .*2$
):
printf '<%.6x>', 1; # prints "<000001>"
printf '<%.*x>', 6, 1; # prints "<000001>"
printf '<%.*2$x>', 1, 6; # prints "<000001>"
printf '<%6.*2$x>', 1, 4; # prints "< 0001>"
If a precision obtained through *
is negative, it counts as having no precision at all.
printf '<%.*s>', 7, "string"; # prints "<string>"
printf '<%.*s>', 3, "string"; # prints "<str>"
printf '<%.*s>', 0, "string"; # prints "<>"
printf '<%.*s>', -1, "string"; # prints "<string>"
printf '<%.*d>', 1, 0; # prints "<0>"
printf '<%.*d>', 0, 0; # prints "<>"
printf '<%.*d>', -1, 0; # prints "<0>"
#size
For numeric conversions, you can specify the size to interpret the number as using l
, h
, V
, q
, L
, or ll
. For integer conversions (d u o x X b i D U O
), numbers are usually assumed to be whatever the default integer size is on your platform (usually 32 or 64 bits), but you can override this to use instead one of the standard C types, as supported by the compiler used to build Perl:
hh interpret integer as C type "char" or "unsigned
char" on Perl 5.14 or later
h interpret integer as C type "short" or
"unsigned short"
j interpret integer as C type "intmax_t" on Perl
5.14 or later. Prior to Perl 5.30 this worked only
with a C99 compiler, hence was unportable before
that release.
l interpret integer as C type "long" or
"unsigned long"
q, L, or ll interpret integer as C type "long long",
"unsigned long long", or "quad" (typically
64-bit integers)
t interpret integer as C type "ptrdiff_t" on Perl
5.14 or later
z interpret integer as C types "size_t" or
"ssize_t" on Perl 5.14 or later
Note that, in general, using the l
modifier (for example, when writing "%ld"
or "%lu"
instead of "%d"
and "%u"
) is unnecessary when used from Perl code. Moreover, it may be harmful, for example on Windows 64-bit where a long is 32-bits.
As of 5.14, none of these raises an exception if they are not supported on your platform. However, if warnings are enabled, a warning of the printf warning class is issued on an unsupported conversion flag. Should you instead prefer an exception, do this:
use warnings FATAL => "printf";
If you would like to know about a version dependency before you start running the program, put something like this at its top:
use v5.14; # for hh/j/t/z/ printf modifiers
You can find out whether your Perl supports quads via Config:
use Config;
if ($Config{use64bitint} eq "define"
|| $Config{longsize} >= 8) {
print "Nice quads!\n";
}
For floating-point conversions (e f g E F G
), numbers are usually assumed to be the default floating-point size on your platform (double or long double), but you can force "long double" with q
, L
, or ll
if your platform supports them. You can find out whether your Perl supports long doubles via Config:
use Config;
print "long doubles\n" if $Config{d_longdbl} eq "define";
You can find out whether Perl considers "long double" to be the default floating-point size to use on your platform via Config:
use Config;
if ($Config{uselongdouble} eq "define") {
print "long doubles by default\n";
}
It can also be that long doubles and doubles are the same thing:
use Config;
($Config{doublesize} == $Config{longdblsize}) &&
print "doubles are long doubles\n";
The size specifier V
has no effect for Perl code, but is supported for compatibility with XS code. It means "use the standard size for a Perl integer or floating-point number", which is the default.
#order of arguments
Normally, sprintf
takes the next unused argument as the value to format for each format specification. If the format specification uses *
to require additional arguments, these are consumed from the argument list in the order they appear in the format specification before the value to format. Where an argument is specified by an explicit index, this does not affect the normal order for the arguments, even when the explicitly specified index would have been the next argument.
So:
printf "<%*.*s>", <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi><mo separator="true">,</mo></mrow><annotation encoding="application/x-tex">x, </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.625em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">x</span><span class="mpunct">,</span></span></span></span>y, $z;
uses $x
for the width, $y
for the precision, and $z
as the value to format; while:
printf '<%*1$.*s>', <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi><mo separator="true">,</mo></mrow><annotation encoding="application/x-tex">x, </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.625em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">x</span><span class="mpunct">,</span></span></span></span>y;
would use $x
for the width and precision, and $y
as the value to format.
Here are some more examples; be aware that when using an explicit index, the $
may need escaping:
printf "%2\$d %d\n", 12, 34; # will print "34 12\n"
printf "%2\$d %d %d\n", 12, 34; # will print "34 12 34\n"
printf "%3\$d %d %d\n", 12, 34, 56; # will print "56 12 34\n"
printf "%2\$*3\$d %d\n", 12, 34, 3; # will print " 34 12\n"
printf "%*1\$.*f\n", 4, 5, 10; # will print "5.0000\n"
If use locale (including use locale ':not_characters'
) is in effect and POSIX::setlocale has been called, the character used for the decimal separator in formatted floating-point numbers is affected by the LC_NUMERIC
locale. See perllocale and POSIX.