Perl printf

See also perldoc -f sprintf

Spec: Function

Classification:   Perl 4   Perl 5 


printf(string, EXPRESSION) 


The printf function has many of the same properties as the print function; however, it lets you better format your output. This is simply done by
placing a field specifier in your string passed followed by a comma-separated EXPRESSION. When the statement is printed to the screen or file, it will replace the field specifier with EXPRESSION in the specified format.

The following is a table of the formatting options along with a brief description of each:
%dDecimal number
%eScientific notation float
%fFixed-point float
%gCompact float
%ldLong decimal number
%loLong octal number
%luLong unsigned number
%lxLong hexadecimal number
%oOctal number
%uUnsigned decimal number
%XUppercase hexadecimal number
%xHexadecimal number


This example defines a string and a numeric value in two variables. The printf function call passes a string and the field specifiers where the variables are then inserted to their locations before the string is printed:

# define the number and string 
$num = 3456.4; 
$string = ("Hello Perl World"); 
# prints 'The cost is $ 3456.40 and the  
# string is Hello Perl World'  
printf("The cost is \$%8.2f and the string is %s", $num, $string); 

This example demonstrates how the printf function can write information to a file. Here I open a file in write mode and assign the string "Hello Perl World" to a variable. The printf function then takes the passed information and writes the informatio n to the file. The "string" field specifier, %s, is replaced with the value of $text when the information is written:

# open file for writing 
open(OUT, "&lgt;test.txt") || die("Error: unable to open file\n"); 
#define the string 
$text = ("Hello Perl World!\n"); 
# print text to that file via its handle 
printf(OUT "The string is: %s", $text); 







See Also:

open, print, sprintf, write