- Perl ›
- builtin functions ›
- here
printf function - formatted string output
Use the printf function to set the format and print the string.
printf "Number%03d%.3f\n", 3, 3.14567;
The above output result is as follows. The integer "3" is padded with 0s to the left so that it has 3 digits. The decimal point "3.14567" is rounded to three decimal places of "3.146".
Number 003 3.146
"%03d" and "%.3f" are called format specifiers. See sprintf function description for more information on format specifiers.
Output to file
Like print function, the fprintf function can also be output by specifying a filehandle using indirect object notation.
# Output to standard error output printf STDERR "Number%03d%.3f\n", 3, 3.14567; # Output to file using file handle printf $fh "Number%03d%.3f\n", 3, 3.14567;
Note that there are no commas behind the filehandle.
For details on how to output, see the explanation of print function.
Export the formatted string to a variable
The printf function is a function that outputs, but you can use sprintf function to write a formatted string to a variable.
my $string = sprintf "Number%03d%.3f\n", 3, 3.14567;
See below for more information on the sprintf function.