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

How can I prepend 0's on a number to get to the 1000th place?

Like if I had the number 100, it would write 0100. If the number was 7, it would be 0007. And if the number was 8010, no 0 would be added.

my $count = 0; foreach my $line (@line) { # these are defined in my script $count++; print $count; # prepend all the requires 0s. }

Replies are listed 'Best First'.
Re: Prepending 0's to 1000
by pg (Canon) on Oct 16, 2004 at 21:54 UTC
    use warnings; use strict; print sprintf("%04d", 7);
Re: Prepending 0's to 1000
by guha (Priest) on Oct 16, 2004 at 21:55 UTC

    You will find good use of the printf/sprintf functions.

    perl -e "printf('%04d', 33)"

    __OUTPUT__
    0033

Re: Prepending 0's to 1000
by perlcapt (Pilgrim) on Oct 16, 2004 at 23:26 UTC
    The key to the sprintf/printf format is the leading 0 in the formating expression %04d. It's that simple. Sprintf and printf come from 'C' standard library functions.
Re: Prepending 0's to 1000
by gaal (Parson) on Oct 17, 2004 at 04:57 UTC
    Just so you know, this type of thing is called "padding", specifically "padding with leading zeros".