Perl uses the
printf functions to write to standard output. Let's look at how they are used.
We've already used
$a = print("hello ", "world", "\n");
would be another way to say
hello world. The return value of
$a in this case will usually be 1.
print (2+3),"hello"; # wrong! prints 5, ignores "hello" print ((2+3),"hello"); # right, prints 5hello print 2+3,"hello"; # also right, prints 5hello
You may wish to have a little more control over your output than
printf function. Fear not: Perl provides a comparable operation with the same name.
printf function takes a list of arguments (enclosed in optional parentheses, like the
printf "%15s %5d %10.2f\n", $s, $n, $r;
This function prints
$s in a 15-character field, then a space, then
$n as a decimal integer in a 5-character field, then another space, then
$r as a floating-point value with 2 decimal places in a 10-character field, and finally a newline.
Among the many formats supported by Perl's
sprintf() functions are the following commonly used ones:
Character with the given number
Signed integer, in decimal
Unsigned integer, in decimal
Unsigned integer, in octal
Unsigned integer, in hexadecimal
Floating-point number, in scientific notation
Floating-point number, in fixed decimal notation
Floating-point number, in %e or %f notation
Between the percent and the format character, you may place one or more of the following flags:
Prefix positive number with a space
Prefix positive number with a plus sign
Left justify within the field
Use zeros, not spaces, to right justify
Minimum field width
Precision: digits after decimal point for floating-point number, maximum length for string, minimum length for integer