For some strings, the input must be in a specific format. sprintf can be used for convenient processing, and no additional processing is required.
The usage of sprintf in Perl is as follows:
Sprintf format, list
For example:
$ Result = sprintf ("% 08d", $ number); give $ number eight leading zeros.
$ Rounded = sprintf ("%. 3f", $ number );
3 digits after the decimal point.
Sprintf allows the following common conversions:
% Percent sign
% C converts a given number to a character
% S string
% D
A signed integer in decimal format.
% U unsigned integer, decimal
% O unsigned integer, octal
% X unsigned integer, hexadecimal
% E floating point number, scientificAlgorithm
% F floating point number, used for fixed decimal counting
% G floating point number, including % E and % F
% 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
% B like % B, but using an upper-case "B" with the # flag
% P a pointer (outputs the Perl value's address in hexadecimal)
% N Special: * stores * The number of characters output so far
Into the next variable in the parameter list
You can change the order by using $1, $2, and so on:
Printf '% 2 $ d % 1 $ d', 12, 34; # prints "34 12"
Printf '% 3 $ d % 1 $ d', 1, 2, 3; # prints "3 1 1"
Printf' <% d> ', 12; # prints "<12>"
Printf' <% + D> ', 12; # prints "<+ 12>"
Printf' <% 6 S> ', 12; # prints "<12>"
Printf' <%-6 S> ', 12; # prints "<12>"
Printf' <% 06 S> ', 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>"
Printf' <% F> ', 1; # prints "<1.000000>"
Printf' <%. 1f> ', 1; # prints "<1.0>"
Printf' <%. 0f> ', 1; # prints "<1>"
Printf' <% E> ', 10; # prints "<1.20.00e + 01>"
Printf' <%. 1E> ', 10; # prints "<1.0e + 01>"
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>"
Printf' <%. 5 S> ', "truncated"; # prints "<trunc>"
Printf' <% 10.5 S> ', "truncated"; # prints "<trunc>"
Printf "% 2/$ d % d/N", 12, 34; # will print "34
"
Printf "% 2/$ d % d/N", 12, 34; # will print "34
4/N"
Printf "% 3/$ d % d/N", 12, 34, 56; # will print "56
4/N"
Printf "% 2/$ * 3/$ d % d/N", 12, 34, 3; # will print "3
N"