next up previous contents
Next: Regular Expressions Up: Basic I/O Previous: Printing Blocks of Text   Contents


Printing to a String

Sometimes it is necessary to prepare text for printing, but to not actually print it. This might be the case if you were composing a report, and needed to wait until all the data was read in order to actually print it, or you may need a text string containing formatted values of variables for repetitive use in a program. Perl makes it very easy to store formatted text in a scalar variable; the sprintf function works exactly like the printf (Section [*]) function, except that, instead of printing formatted text, it returns a scalar character variable containing that printed text.

Suppose we have an array containing prices, and we wish to calculate taxes on these prices, based on a tax rate of 7.5%. If we simply compute the taxes, and print the resulting variables, we may print numbers with more than two decimal places, which is inappropriate. We could create a corresponding array of formatted taxes as follows:

     foreach $p (@prices){
         push(@ftaxes,sprintf("%5.2f",$p * 0.075);
     }
Each of the elements of @ftaxes will be of length 5, right justified with two decimal places, making them suitable for printing in a table.
next up previous contents
Next: Regular Expressions Up: Basic I/O Previous: Printing Blocks of Text   Contents
Phil Spector 2002-10-18