"Perl for Perl Newbies" - Part 4The sprintf functionFlags to the conversions

2.2. Flags to the conversions

One can put various flags between the percent sign and before the conversion character, which alter the output. Here is a list of them:

spacePrefix positive number with a space
+Prefix positive number with a + sign
-Left justify the output within the specified field
0Use zeros, not spaces to right justify.
#Prefix non-zero octal with 0, non-zero hex with "0x", and non-zero binary with "0b"

For example (taken from perldoc -f sprintf):

printf '<% d>', 12;   # prints "< 12>"
printf '<%+d>', 12;   # prints "<+12>"
printf '<%6s>', 12;   # prints "<    12>"
printf '<%-6s>', 12;  # prints "<12    >"
printf '<%06s>', 12;  # prints "<000012>"
printf '<%#x>', 12;   # prints "<0xc>"

Note that printf formats its arguments using sprintf and then prints them using print.


Written by Shlomi Fish