Полезная информация

Programming Perl

Programming PerlSearch this book
Previous: 3.2.155 splitChapter 3
Next: 3.2.157 sqrt

3.2.156 sprintf

sprintf FORMAT, LIST

This function returns a string formatted by the usual printf conventions. The FORMAT string contains text with embedded field specifiers into which the elements of LIST are substituted, one per field. Field specifiers are roughly of the form:


where the m and n are optional sizes whose interpretation depends on the type of field, and x is one of:

dDecimal integer
eExponential format floating-point number
fFixed point format floating-point number
gCompact format floating-point number
ldLong decimal integer
loLong octal integer
luLong unsigned decimal integer
lxLong hexadecimal integer
oOctal integer
uUnsigned decimal integer
xHexadecimal integer
XHexadecimal integer with upper-case letters

The various combinations are fully documented in the manpage for printf(3), but we'll mention that m is typically the minimum length of the field (negative for left justified), and n is precision for exponential formats and the maximum length for other formats. Padding is typically done with spaces for strings and zeroes for numbers. The * character as a length specifier is not supported. But, you can easily get around this by including the length expression directly into FORMAT, as in:

$width = 20; $value = sin 1.0;
foreach $precision (0..($width-2)) {
    $output_arr[$precision] = sprintf "%${width}.${precision}f", $value;

Previous: 3.2.155 splitProgramming PerlNext: 3.2.157 sqrt
3.2.155 splitBook Index3.2.157 sqrt