9.2 Formatted Output and the printf Operator
Whilst the print command is useful much of the time for outputting basic messages there is a much more flexible and powerful output operator. This is the printf formatted print operator. If you are familiar with the printf function in the C programming language then you are in luck . the two forms of printf work comparably and you will quickly get up to speed on Perl printf. If you are new to printf you will very quickly become familiar with the concept.
The printf operator takes arguments in stages. The first argument is referred to as the .format string.. This governs how the string to be displayed will be formatted in terms of both any text to be displayed and both the format and location of any values that are to be output to the standard output stream.
The remaining arguments define what values are to be placed in the various locations and formats defined in the format string.
The format string is made up of optional text and .conversions.. The conversions control how each subsequent corresponding value argument is to be displayed. These conversions always begin with a % character to distinguish them from other text in the format string.
Lets start with a simple example. Suppose we have two scalar values one a string representing a name and the other an integer representing a number of days. We want to display a sentence that when run will include these two values in a sentence:
$days=3
$name = "James"
printf "My name is %s and I have reading Picking Up Perl for %d days\n", $name, $days;
In this example we have a string that contains two conversions. The first is the %s conversion for our name string. This tells printf that the first argument after the format string is to be treated as a string value and displayed at the location in the template where the %s is located.
The second conversion is a %d which will tells printf to treat the second argument after the format string as a decimal integer and display it in the location of the %d conversion.
The output from the above printf operation would be:
My name is James and I have been reading Picking Up Perl for 5 days.
Perl printf supports a number of conversions:
%% a percent sign
%c a character with the given number
%s a string
%d a signed integer, in decimal
%u an unsigned integer, in decimal
%o an unsigned integer, in octal
%x an unsigned integer, in hexadecimal
%e a floating-point number, in scientific notation
%f a floating-point number, in fixed decimal notation
%g a floating-point number, in %e or %f notation