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

Hi Monks, I have the doubt in sprintf.
I need to fill the leading zeros for my given no of digit.
I have tried the following but not getting the correct result.
Do u have these problem in previous?. please suggest me to solve the problem.

$dig=4; $inc=5; $res=sprintf("%0$digd", $inc); print $res; #output should be #0005

Thanks in advance for your suggestion.

Replies are listed 'Best First'.
Re: sprintf formatting doubt
by murugu (Curate) on Feb 11, 2005 at 06:53 UTC

    Hi perlsen,

    u have to write that sprintf as,

    $res=sprintf("%0${dig}d",$inc);

    Regards,
    Murugesan Kandasamy.

Re: sprintf formatting doubt
by matija (Priest) on Feb 11, 2005 at 08:10 UTC
    You could just use the standard printf sintax, and write sprintf "%0*d",$dig,$inc; Here is an example:
    perl -e '$a=150; $b=6; print sprintf "%0*d\n",$b,$a;' 000150