Jun 01

How to format a string with leading zeros?

Category: Linux,Perl   — Published by tengo on June 1, 2008 at 9:09 am

A quick reminder:

How do I pad a string so that a number or string gets leading zeros?


By using sprintf:

my $number = 123;
$number = sprintf("%07d", $number);
print $number;

Output: "0000123"

after the %: "0" is the character to add, <number>d is the amount of digits (that's why it's "d") to add. See the documentation for sprintf.