Search code examples
perl

Add zero prefix of the number in Perl for date conversion


I'm trying to add zero prefix of the number. I have tried the code as follows,

Code:

use strict;
   use warnings;
   my $day = 11;
   for (my $i=1; $i<=$day ; $i++) {
       if( $i < 10 ) {
            $i = "0$i";
        }
        print "Number of day: $i\n";
    }

Output:

01
002
0003
00004
...
...

But I want the output like below,

01
02
03
04
...

Please help me on this thanks in advance.


Solution

  • Try this:

    use strict;
    use warnings;
    my $day = 11;
    for (my $i=1; $i<=$day; $i++) {
        if( $i < 10 ) {
            $i = sprintf("%02d",$i);
        }
        print "Number of day: $i\n";
    }