|
Getting
It to Look the Way You Want
Randal L. Schwartz
For the most part, Perl programmers tend to use the nice standby print operator
for output, or drift occasionally into the realm of formats to quickly lay out
a look for a customized report. However, the often overlooked printf
operator provides a nice amount of custom control to get those output strings
to look exactly the way you want.
The printf operator takes a format string, and zero or more values.
The format string drives the whole process. With a few exceptions, each percent
% field in the format string matches up with one of the additional
values, defining how the value will appear in the output. For example:
printf "my string %s has %d characters.\n", $str, length($str);
Here, the %s field calls for a string value, provided by $str.
Similarly, the %d field calls for a decimal integer, provided by
the length($str) computation. The parameters are evaluated in a
list context, so we could have also used the following code to accomplish the
same output:
@output = ($str, length($str)); printf "my string %s has %d characters.\n",
@output;
This gets interesting if we don't know the length of @output,
because we need a %-field for each element of @output,
but since we set it up ourselves here, that's not a problem.
Besides %s for string, and %d for decimal integer,
another common format is %f for floating point:
printf "he has $%f in his account\n", 3.5
|