A Better Way to print

Previous Table of Contents Next

A Better Way to print

The print function is a very simple output function; it provides almost no formatting capability. To have fine-grained control over the appearance of expression values, such as left and right alignment, number of digits of decimal precision, and fixed-width output, you must use the Perl printf function instead.

Formatted Printing with printf

The printf function was borrowed (almost verbatim) from the C programming language, but other languages have a similar function, such as BASIC's print using function. The syntax for printf is as follows:

printf formatstring, list

printf filehandle formatstring, list

The formatstring is a string that describes the format of the output, which is described shortly. The list is a list of values that you want printf to displaysomewhat similar to the arguments to the print function. Normally, printf displays its output to the STDOUT filehandle, but, as with print, if you specify a filehandle, printf uses that filehandle instead. Note that no comma is used between the filehandle name and the formatstring.

Specifying the Field Formats

The formatstring is a string literal (usually) or a scalar that describes what the output should look like. Every character in the formatstring is printed literally, except those character sequencesbeginning with a %. The % indicates the start of a field specifier. The format of a field specifier is shown here:

As seen in the figure, field specifiers have the form %-w.dx, where w is the total desired width of the field. d is the number of positions to the right of the decimal point (for numbers) and the total allowable width of the field (for strings). x indicates what kind of data is to be printed. A minus sign (a hyphen) before the w specifier indicates that the field is to be left-justified within w characters; otherwise, it's right-justified. Only the % and x are mandatory. Table 9.1 lists some of the different types of field specifiers (that is, values for the x position).

Table 9.1. Partial List of printf Field Specifier Types

Field Type







Decimal integer; fraction is truncated


Floating-point number

A full list of field specifier types is included in the online manual. You can view it by typing perldoc -f printf at a command prompt.

The following are some examples of using printf:

printf("%20s", "Jack");       # Right-justify "Jack" in 20-characters

printf("%-20s", "Jill");      # Left-justify "Jill" in 20 characters


printf("%6.2f", $amt);        # prints "    7.12"


printf("%6.2f", $amt);        # prints "    7.13", extra digits rounded

printf("%c", 65);             # prints ASCII character for 65, "A"


printf("%6.2f", $amt);        # prints "   9.40"

printf("%6d", $amt);          # prints "      9"

Each field specifier uses one item from the list, as shown in the following figure. For each item, there should be a field specifier; for every field specifier, there should be a list element.

To print leading zeros in a number, simply put a 0 in front of the width in the field specifier, as follows:

printf("%06.2f", $amt);  # prints "009.40"

What if you want a literal percent sign in your output? The sequence %% represents a percent sign:

$newprice = 1.449;

$oldprice = 1.229;

printf("The price went up by %3.1f%%!\n", 100*(($newprice/$oldprice) - 1));

#    prints "The price went up by 17.9%!"

Formatted Output to a String

The sprintf function is nearly identical to printf, except that instead of being printed, the formatted output is returned from sprintfready for you to assign to a scalar or use in another expression, as you can see here:


# Format result nicely to 2-decimals

$moonweight = sprintf("%.2f", $weight / 6);

print "You weigh $moonweight on the moon.";

Remember that printf and sprintf with the %f format specifier will round your results to the specified number of decimal places for you.

    Previous Table of Contents Next
    © 2000- NIV