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 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.