I want to use Perl's sprintf to zerofill a variable.
sprintf("%08d", $var);
But I want to dynamically determine how many digits to zerofill.
How do I replace the "8" in sprintf("%08d", $var)
with a variable called $zerofill
?
I want to use Perl's sprintf to zerofill a variable.
sprintf("%08d", $var);
But I want to dynamically determine how many digits to zerofill.
How do I replace the "8" in sprintf("%08d", $var)
with a variable called $zerofill
?
sprintf
andprintf
support the*
notation (this has worked since at least 5.8):I needed to do something slightly different: zero pad a floating point value and get an exact length.
In my case I need exactly 12 bytes including the decimal point. It is slightly trickier than what you have above. Here it is in case anyone needs this:
Say $inputVal is a string passed in from somewhere with a value like 1001.1. Note that it should be less than 12 characters for this to work reliably
The first argument to sprintf is just a string:
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.