Always use *
in your format specifier to unambiguously indicate variable width! This is similar to the advice to use printf "%s", $str
rather than printf $str
.
From the perlfunc documentation on sprintf
:
(minimum) width
Arguments are usually formatted to be only as wide as required to display the given value. You can override the width by putting a number here, or get the width from the next argument (with *
) or from a specified argument (with e.g. *2$
):
printf '<%s>', "a"; # prints "<a>"
printf '<%6s>', "a"; # prints "< a>"
printf '<%*s>', 6, "a"; # prints "< a>"
printf '<%*2$s>', "a", 6; # prints "< a>"
printf '<%2s>', "long"; # prints "<long>" (does not truncate)
If a field width obtained through *
is negative, it has the same effect as the -
flag: left-justification.
For example:
#! /usr/bin/perl
use warnings;
use strict;
my $cols = 10;
$_ = "foo!";
printf "%*s\n", $cols, $_;
print "0123456789\n";
Output:
foo!
0123456789
With the warnings
pragma enabled, you'll see warnings for non-numeric width arguments.