Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Prepending 0's to 1000

by Anonymous Monk
on Oct 16, 2004 at 21:45 UTC ( [id://399827]=perlquestion: print w/replies, xml ) Need Help??

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".

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://399827]
Approved by Arunbear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2024-03-28 10:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found