I want to use Perl's sprintf to zerofill a variable.
sprintf("%08d", $var);
but I want the dynamically determine how many digits to zero fill.
How do I replace the "8" in sprintf("%08d", $var)
with a variable called $zerofill
.
Thanks.
I want to use Perl's sprintf to zerofill a variable.
sprintf("%08d", $var);
but I want the dynamically determine how many digits to zero fill.
How do I replace the "8" in sprintf("%08d", $var)
with a variable called $zerofill
.
Thanks.
The first argument to sprintf is just a string:
my $num = 9;
my $filled = sprintf "%0${zerofill}d", $number;
Notice the braces to set apart the variable name from the rest of the string.
We have this particular problem as a slightly clever exercise in Learning Perl to remind people that strings are just strings. :)
However, as mobrule points out in his answer, sprintf has many features to give you this sort of flexibility. The documentation for such a seemingly simple function is quite long and there are a lot of goodies in it.
sprintf
and printf
support the *
notation (this has worked since at least 5.8):
printf "%0*d", 9, 12345;
000012345
printf '$%*.*f', 8, 2, 456.78;
$ 456.78