jpk236 has asked for the wisdom of the Perl Monks concerning the following question:

I did a little searching, but didn't immediately find anything relevant. My question is if there is an eloquent way to do number padding (ie: turn 5 into 05).

Anything will be better than my current solution:
$num = "0".$num if ($num < 10);

I feel something like this would be cool:
$num = pad($num,1);
where $num is the input and 1 is the number of zeroes to prepend.

- Justin

Replies are listed 'Best First'.
Re: Number Padding
by johnnywang (Priest) on May 27, 2005 at 17:18 UTC
Re: Number Padding
by djohnston (Monk) on May 27, 2005 at 17:19 UTC
    See perldoc -f sprintf.
Re: Number Padding
by marnanel (Beadle) on May 27, 2005 at 17:19 UTC
    Sure, just use sprintf.
    my $padded = sprintf "%02d", $num;
Re: Number Padding
by holli (Abbot) on May 27, 2005 at 17:20 UTC
    $num = sprintf ("%02d", $num);


    holli, /regexed monk/
Re: Number Padding
by mikeraz (Friar) on May 27, 2005 at 17:22 UTC

    Why won't sprintf function for your purposes?

    #!/usr/bin/perl foreach $p ( 2..5 ) { print sprintf ("%0${p}d\n", $p); } __END__ prints: 02 003 0004 00005

      Don't forget the star syntax:

      sprintf '%0*d', $len, $value;

      ihb

      See perltoc if you don't know which perldoc to read!

Re: Number Padding
by omega_monk (Scribe) on May 27, 2005 at 17:24 UTC
    I just learned about the sprintf function... There may be some useful info there. Also check out sprintf.

    Update: added the link to sprintf
Re: Number Padding
by jpk236 (Monk) on May 27, 2005 at 17:27 UTC
    *smacks head*
    duh! thanks guys!

    - Justin
Re: Number Padding
by tcf03 (Deacon) on May 27, 2005 at 17:55 UTC
    This isnt perl but I once had to do this with directory names in shell script
    mkdir `awk -vmax=31 'BEGIN{for (i=1;i<=max;i++) printf "%.2d ",i; prin +t}'`
    is one of the cooler ways ive found to do this, then there is seq
    mkdir `seq -w 1 31`
    as I said not perl and a bit off the beaten track...
    Ted
    --
    "That which we persist in doing becomes easier, not that the task itself has become easier, but that our ability to perform it has improved."
      --Ralph Waldo Emerson