How to use sprintf to null a variable variable in Perl?

I want to use Perl sprintf for a null variable.

sprintf("%08d", $var);

But I want to dynamically determine how many digits should be zero.

How to replace "8" in sprintf("%08d", $var)with a variable with a name $zerofill?

+3
source share
3 answers

The first sprintf argument is just a string:

 my $zerofill = 9;
 my $number = 1000;
 my $filled = sprintf "%0${zerofill}d", $number;

Pay attention to braces to separate the variable name from the rest of the string.

We have this particular issue as a slightly smart exercise in Learning Perl to remind people that strings are just strings. :)

, mobrule , sprintf , โ€‹โ€‹. , , , .

+14

sprintf printf * ( 5.8):


printf "%0*d", 9, 12345;

000012345

printf '$%*.*f', 8, 2, 456.78;

$  456.78
+13

- : .

12 , . , , . , - :

$inputVal - , - , 1001.1. , 12

 # 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);
+2

Source: https://habr.com/ru/post/1737546/


All Articles