4.4. The printf Function
The printf function prints a formatted string to the selected filehandle, the default being STDOUT. It is like the printf function used in the C and awk languages. The return value is 1 if printf is successful and 0 if it fails.
The printf function consists of a quoted control string that may include format specifications. The quoted string is followed by a comma and a list of comma-separated arguments, which are simply expressions. The format specifiers are preceded by a % sign. For each % sign and format specifier, there must be a corresponding argument. (See Tables 4.4 and 4.5.)
Table 4.4. Format Specifiers
Conversion | Definition |
---|
%b | Unsigned binary integer |
%c | Character |
%d, i | Decimal number |
%e | Floating point number in scientific notation |
%E | Floating point number in scientific notation using capital E |
%f, %F | Floating point number |
%g | Floating point number using either e or f conversion, whichever takes the least space |
%G | Floating point number using either e or f conversion, whichever takes the least space |
%ld, %D | Long decimal number |
%lu, %U | Long unsigned decimal number |
%lo, %O | Long octal number |
%p | Pointer (hexadecimal) |
%s | String |
%u | Unsigned decimal number |
%x | Hexadecimal number |
%X | Hexadecimal number using capital X |
%lx | Long hexidecimal number |
%% | Print a literal percent sign |
Table 4.5. Flag Modifiers
Conversion | Definition |
---|
%- | Left-justification modifier |
%# | Integers in octal format are displayed with a leading 0; integers in hexadecimal form are displayed with a leading 0x |
%+ | For conversions using d, e, f, and g, integers are displayed with a numeric sign, + or - |
%0 | The displayed value is padded with zeros instead of whitespace |
%number | Maximum field width; for example, if number is 6, as in %6d, maximum field width is six digits |
%.number | Precision of a floating point number; for example, %.2f specifies a precision of two digits to the right of the decimal point, and %8.2 represents a maximum field width of eight, where one of the characters is a decimal point followed by two digits after the decimal point |
Placing the quoted string and expressions within parentheses is optional.
Example 4.17.

The string to be printed is enclosed in double quotes. The first format specifier is %s. It has a corresponding argument, John, positioned directly to the right of the comma after the closing quote in the control string. The s following the percent sign is called a conversion character. The s means string conversion will take place at this spot. In this case John will replace the %s when the string is printed. The %d format specifies that the decimal (integer) value 50 will be printed in its place within the string.
|
Flag modifiers are used after the % to further define the printing; for example, %-20s represents a 20-character left-justified field.
When an argument is printed, the field holds the value that will be printed, and the width of the field is the number of characters the field should contain. The width of a field is specified by a percent sign and a number representing the maximum field width, followed by the conversion character; for example, %20s is a right-justified 20-character string; %-25s is a left-justified 25-character string; and %10.2f is a right-justified 10-character floating point number, where the decimal point counts as one of the characters and the precision is two places to the right of the decimal point. If the argument exceeds the maximum field width, printf will not truncate the number, but your formatting may not look nice. If the number to the right of the decimal point is truncated, it will be rounded up; for example, if the formatting instruction is %.2f, the corresponding argument, 56.555555, would be printed as 56.6.
Example 4.18.
Code View: (The Script)
#!/usr/bin/perl
1 printf "Hello to you and yours %s!\n","Sam McGoo!";
2 printf("%-15s%-20s\n", "Jack", "Sprat");
3 printf "The number in decimal is %d\n", 45;
4 printf "The formatted number is |%10d|\n", 100;
5 printf "The number printed with leading zeros is |%010d|\n", 5;
6 printf "Left-justified the number is |%-10d|\n", 100;
7 printf "The number in octal is %o\n",15;
8 printf "The number in hexadecimal is %x\n", 15;
9 printf "The formatted floating point number is |%8.2f|\n",
14.3456;
10 printf "The floating point number is |%8f|\n", 15;
11 printf "The character is %c\n", 65;
(Output)
1 Hello to you and yours Sam McGoo!
2 Jack Sprat
3 The number in decimal is 45
4 The formatted number is | 100|
5 The number printed with leading zeros is |0000000005|.
6 Left-justified the number is |100 |
7 The number in octal is 17
8 The number in hexadecimal is f
9 The formatted floating point number is | 14.35|
10 The floating point number is |15.000000|
11 The character is A
The quoted string contains the %s format conversion specifier. The string Sam Magoo is converted to a string and replaces the %s in the printed output. The string Jack has a field width of 15 characters and is left-justified. The string Sprat has a field width of 20 characters and is also left-justified. Parentheses are optional. The number 45 is printed in decimal format. The number 100 has a field width of 10 and is right-justified. The number 5 has a field width of 10, is right-justified, and is preceded by leading zeros rather than whitespace. If the modifier 0 is placed before the number representing the field width, the number printed will be padded with leading zeros if it takes up less space than it needs. The number 100 has a field width of 10 and is left-justified. The number 15 is printed in octal. The number 15 is printed in hexadecimal. The number 14.3456 is given a field width of eight characters. One of them is the decimal point; the fractional part is given a precision of two decimal places. The number is then rounded up. The number 15 is given a field width of eight characters, right-justified. The default precision is six decimal places to the right of the decimal point. The number 65 is converted to the ASCII character A and printed.
|
4.4.1. The sprintf Function
The sprintf function is just like the printf function, except it allows you to assign the formatted string to a variable. sprintf and printf use the same conversion tables (Tables 4.4 and 4.5). Variables are discussed in Chapter 5, "What's in a Name."
Example 4.19.
(The Script)
1 $string = sprintf("The name is: %10s\nThe number is: %8.2f\n",
"Ellie", 33);
2 print "$string";
(Output)
2 The name is: Ellie
The number is: 33.00
The sprintf function follows the same rules as printf for conversion of characters, strings, and numbers. The only real difference is that sprintf allows you to store the formatted output in a variable. In this example, the formatted output is stored in the scalar variable $string. The \n inserted in the string causes the remaining portion of the string to be printed on the next line. Scalar variables are discussed in Chapter 5, "What's in a Name." Parentheses are optional. The value of the variable is printed showing the formatted output produced by sprintf.
|
4.4.2. Printing without Quotes—The here document
The Perl here document is derived from the UNIX shell here document. It allows you to quote a whole block of text enclosed between words called user-defined terminators. From the first terminator to the last terminator, the text is quoted, or you could say "from here to here" the text is quoted. The here document is a line-oriented form of quoting, requiring the << operator followed by an initial terminating word and a semicolon. There can be no spaces after the << unless the terminator itself is quoted. If the terminating word is not quoted or double quoted, variable expansion is performed. If the terminating word is singly quoted, variable expansion is not performed. Each line of text is inserted between the first and last terminating word. The final terminating word must be on a line by itself, with no surrounding whitespace.
Perl, unlike the shell, does not perform command substitution (backquotes) in the text of a here document. Perl, on the other hand, does allow you to execute commands in the here document if the terminator is enclosed in backquotes. (Not a good idea.)
Here documents are used extensively in CGI scripts for enclosing large chunks of HTML tags for printing.
Example 4.20.
(The Script)
1 $price=1000; # A variable is assigned a value.
2 print <<EOF;
3 The consumer commented, "As I look over my budget, I'd say
4 the price of $price is right. I'll give you \$500 to start."\n
5 EOF
6 print <<'FINIS';
The consumer commented, "As I look over my budget, I'd say
7 the price of $price is too much.\n I'll settle for $500."
8 FINIS
9 print << x 4;
Here's to a new day.
Cheers!
10
print "\nLet's execute some commands.\n";
# If terminator is in backquotes, will execute OS commands
11 print <<'END';
echo Today is
date
END
(Output)
3 The consumer commented, "As I look over my budget, I'd say
the price of 1000 is right. I'll give you $500 to start."
6 The consumer commented, "As I look over my budget, I'd say
the price of $price is too much. \n I'll settle for $500."
9 Here's to a new day.
Cheers!
Here's to a new day.
Cheers!
Here's to a new day.
Cheers!
Here's to a new day.
Cheers!
11 Let's execute some commands.
Today is
Fri Oct 27 12:48:36 PDT 2007
A scalar variable, $price, is assigned the value 1000. Start of here document. EOF is the terminator. The block is treated as if in double quotes. If there is any space preceding the terminator, then enclose the terminator in double quotes, such as "EOF". All text in the body of the here document is quoted as though the whole block of text were surrounded by double quotes. The dollar sign has a special meaning when enclosed in double quotes. Since the text in this here document is treated as if in double quotes, the variable has special meaning here as well. The $ is used to indicate that a scalar variable is being used. The value of the variable will be interpreted. If a backslash precedes the dollar sign, it will be treated as a literal. If special backslash sequences are used, such as \n, they will be interpreted. End of here document marked by matching terminator, EOF. There can be no space surrounding the terminator. By surrounding the terminator, FINIS, with single quotes, the text that follows will be treated literally, turning off the meaning of any special characters, such as the dollar sign or backslash sequences. Text is treated as if in single quotes. Closing terminator marks the end of the here document. The value x 4 says that the text within the here document will be printed four times. The x operator is called the repetition operator. There must be a blank line at the end of the block of text, so that the here document is terminated. The blank line is required here to end the here document. The terminator is enclosed in backquotes. The shell will execute the commands between 'END' and END. This example includes UNIX commands. If you are using another operating system, such as Windows or Mac OS, the commands must be compatible with that operating system.
|
Here Documents and CGI
The following program is called a CGI (Common Gateway Interface) program, a simple Perl program executed by a Web server rather than by the shell. It is just like any other Perl script with two exceptions:
There is a line called the MIME line (e.g., Content-type: text/html) that describes what kind of content will be sent back to the browser.
The document consists of text embedded with HTML tags, the language used by browsers to render text in different colors, fonts faces, types, etc. Many CGI programmers take advantage of the here document to avoid using the print function for every line of the program.
CGI programs are stored in a special directory called cgi-bin, which is normally found under the Web server's root directory. See Chapter 16, "CGI and Perl: The Hyper Dynamic Duo," for a complete discussion of CGI.
To execute the following script, you will start up your Web browser and type in the Location box: http://servername/cgi-bin/scriptname. See Figure 4.1.
Example 4.21.
#!/bin/perl
# The HTML tags are embedded in the here document to avoid using
# multiple print statements
1 print <<EOF; #here document in a CGI script
2 Content-type: text/html
3
4 <HTML><HEAD><TITLE>Town Crier</TITLE></HEAD>
<H1><CENTER>Hear ye, hear ye, Sir Richard cometh!!</CENTER></H1>
</HTML>
5 EOF
1 | The here document starts here. The terminating word is EOF. The print function will receive everything from EOF to EOF. | 2 | This line tells the browser that the type of content that is being sent is text mixed with HTML tags. This line must be followed by a blank line. | 4 | The body of the document consists of text and HTML tags. | 5 | The word EOF marks the end of the here document. |
|