Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use sprintf to add padding zeroes on the right in Perl?

Tags:

perl

I want to pad zeroes to the right side of a given number using sprintf.

Example: if the number is 0715 then I want to pad zeroes to the right side creating a new six-digit number:

Input-->0715
Output-->071500
like image 237
Bastian Avatar asked Aug 20 '15 08:08

Bastian


2 Answers

There is no pattern for sprintf to format a string left-justified with zeroes instead of spaces.

These are all the flags that perldoc lists:

space   prefix non-negative number with a space
+       prefix non-negative number with a plus sign
-       left-justify within the field
0       use zeros, not spaces, to right-justify
#       ensure the leading "0" for any octal,
        prefix non-zero hexadecimal with "0x" or "0X",
        prefix non-zero binary with "0b" or "0B"

If you insist on using sprintf, you will have to go with - to left-justify within the field, which will give you blank spaces on the right. Then you need to change those to zeroes. You can do that with the tr transliteration operator. I'm using the shorter form with the /r modifier that makes tr/// return the value instead of just changing the lvalue $foo.

my $foo = '0715';
print sprintf('%-6s', $foo) =~ tr/ /0/r;

Output:

071500
like image 117
simbabque Avatar answered Oct 05 '22 19:10

simbabque


You can also do it using substr. Append six 0s and get the string from 0th to 6th index. But obviously as Sobrique said you can't do it treating it as number.

my $num = '0715';
print substr $num.'0'x6,0,6;
like image 30
Arunesh Singh Avatar answered Oct 05 '22 18:10

Arunesh Singh