next up previous contents
Next: Filehandles Up: Basic I/O Previous: The empty diamond operator   Contents


Printing

As we've seen the print function is the basic tool for printing in perl. The print function takes a list of arguments and prints them to the standard output (often the computer screen). By default, print places no characters between the comma-separated elements comprising its arguments, and adds no newline or other character to the end of each line. (To modify the inter-item separator, change the value of the variable $,; to change the inter-record separator, change the value of the variable $\.) Many printing tasks can be simplified by remembering that, if you enclose the arguments to print in double quotes, variable interpolation will take place. Unfortunately, things like function calls are not interpolated inside of double quotes, and either the character concatenation operator (.) must be used to build up the line to be printed, or you must use several print statements, each printing a separate part of what you want printed. An example can be seen in Section 7.2, where a heading was printed for each file read. The statement
     print '=' x 10 . " $ARGV " . '=' x 10 . "\n";
is very awkward, requiring four separate sets of quotes. In cases like these, the printf (formatted print) function is very helpful. The first argument to printf is a control string, surrounded by double quotes; literal characters are printed as they appear, but a percent sign (%) in the control string indicates that a variable substitution will take place, using the arguments following the control string. Depending on what follows the percent sign, the corresponding argument will be interpreted as shown in Table [*]. Thus a printf statement to give the same result as the previous print statement could be
     printf("%s $ARGV %s\n",'=' x 10,'=' x 10);

By default, printf will right justify its corresponding argument in the field width specified; for left justification, put a minus sign (-) immediately after the percent sign of the appropriate format code.


Table: Format codes for the printf function
Code Meaning
%i Integer
%f Floating point number
%wi Integer, field width of w
%w.df Field width of w, d decimal places
%0wi Integer, field width of w with leading zeroes
%s Character String
%x Hexadecimal Value



next up previous contents
Next: Filehandles Up: Basic I/O Previous: The empty diamond operator   Contents
Phil Spector 2002-10-18