introduction to web programming Using the printf and sprintf functions The Perl printf is much like the printf function in C and awk in that it takes a string to be formatted and a list of format arguments, applies the formatting to the string, and then typically prints the formatted string to standard output, which in our case, is the Web browser.

The printf syntax uses a double quoted string which includes special format markers followed by a comma-delimited list of arguments to be applied to those markers. The format markers are typically in the form of a percent sign followed by a control character.

For example, the generic format of printf might look like the following code:

    printf ("[some text] %[format] [other text]",
    [argument to be formatted]);

In usage, we might use the %s formatting argument specifying a string and the %d formatting argument specifying a digit using the following syntax:

    #!/usr/local/bin/perl
    print "Content-type: text/html\n\n";
    $name = "Selena Sol";
    $age = 28;
    printf ("My name is %s and my age is %d.\n",
             $name, $age);

The code above would produce the following output in the Web browser window:

    My name is Selena Sol and my age is 28.

In reality, the printf function is rarely used in Perl CGI since, unlike C which almost demands the use of printf, Perl has much easier ways of printing. However, the printf routines are essential for another, more useful (to CGI developers) function, sprintf.

Unlike printf, sprintf takes the formatted output and assigns it to a variable rather than outputting it to standard output (<STDOUT>), using the following generic syntax:

    $variable_name = sprintf ("[some text]
    %[format] [other text]", [string to be
    formatted]);

A good example of using sprintf might come from a shopping cart script. In this script, we need to format subtotals and grand totals to two decimal places so that prices come out to numbers like "$99.00" or "$98.99" rather than "99" or "98.99876453782". Below is a snippet of code which uses sprintf to format a price string to two decimal places.

    $option_grand_total = sprintf ("%.2f\n",
    $unformatted_option_grand_total);

In this example, the variable, $unformatted_option_grand_total is formatted using the "%.2f" argument which formats (%) the string to two decimal places (.2f).

There are a multitude of formatting arguments besides "%s", "%d" and "%f", however. The following Table lists several useful ones.

Format character Description
c Character
s String
d Decimal Number
x Hexadecimal Number
o Octal Number
f Floating Point Number

Previous | Next | Table of Contents