Appendix A. sprintf


Appendix A. sprintf

For whatever reason, most Perl books don't actually document the sprintf and printf operators. Instead, they say something like "check the man page for sprintf(3) ." I've always thought it would be handy if at least one of the Perl books on my shelf contained a quick reference to sprintf , thoughso here it is.

The arguments to Perl's sprintf operator are a format string and a list of values to be formatted. The format string contains conversion specifiers, which begin with the percent sign character % and end with one of several characters like d , f , or x . The specifiers are replaced with their corresponding formatted values, and the result is a string:

 $str = sprintf '%d', 3.1416; 

3.1416 formatted as decimal integer: "3" .

 $str =    sprintf 'TOTAL: $%7.2f', 49.95; 

49.95 in seven-character wide field, right-justified:

"TOTAL: $ 49.95"

 $str = sprintf '0%o 0x%x', 15, 15; 

Hex and octal integers:

"017 0xf"

The printf operator works like sprintf , except that it sends the formatted string to standard output, or to some other filehandle if specified:

 printf 'TOTAL: $%7.2f', 49.95; 

Prints to standard output:

"TOTAL: $ 49.95"

 printf STDERR    'elapsed: %.1f min', $time/60; 

Note: no comma after filehandle, as usual.

That's all there is to it, except for a description of sprintf 's conversion specifiers. The rest of this Appendix is a summary of the conversion specifiers and their features.



Effective Perl Programming. Writing Better Programs with Perl
Effective Perl Programming: Writing Better Programs with Perl
ISBN: 0201419750
EAN: 2147483647
Year: 1996
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net