format printf
---------------
##.## %2.2f
####.## %4.2f
To print a string with fixed-length elements, use the
printf( ) format %n.ms where
n is the length of the field allocated for the
string and m is the maximum number of characters
to take from the string. For example:
printf "[%5.3s][%10.10s][%30.30s]\n",
12345, "John Doe", "1234 Abbey Road"
prints:
[ 123][ John Doe][ 1234 Abbey Road]
Notice that the first string was allocated five characters in the
output, but only three were used because m=5 and
n=3 (%5.3s). If you want to
ensure that the text will always be correctly aligned without being
truncated, n should always be greater than or
equal to m.
You can change the alignment to the left by adding a minus sign
(-) after the %. For example:
printf "[%-5.5s][%-10.10s][%-30.30s]\n",
123, "John Doe", "1234 Abbey Road"
prints:
[123 ][John Doe ][1234 Abbey Road ]
You can also use a plus sign (+) for the
right-side alignment. For example:
printf "[%+5s][%+10s][%+30s]\n",
123, "John Doe", "1234 Abbey Road"
prints:
[ 123][ John Doe][ 1234 Abbey Road]
Another alternative to format( ) and
printf( ) is to use the
Text::Reform module from CPAN.
In the examples above we've printed the number
123 as a string (because we used the
%s format specifier), but numbers can also be
printed using numeric formats. See perldoc -f
sprintf for full details.