How do I use sprintf to zero fill to a variable length in Perl?

删除回忆录丶 提交于 2019-12-04 10:07:27
brian d foy

The first argument to sprintf is just a string:

 my $zerofill = 9;
 my $number = 1000;
 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
Tereus Scott

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

 # This will give us extra zeros, but the string may be too long
 my $floatVal = sprintf('%*.*f', 12, 12, $inputValue);

 # This will remove any extra zeros
 $result = substr($floatVal, 0, 12);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!