adding Leading zeros

In perl, I have a number, say  2462. (it can be any whole number)
I would like to insert zeros at the beginning so that it always becomes a string of 8 characters.
ie  00002462
What is the best way to do this?
Lee5Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
HalldorGConnect With a Mentor Commented:
$myvar=sprintf("%08d",2345);
0
 
ozoCommented:
printf"%08d",2462;
0
 
Lee5Author Commented:
That prints the number but how do I make it into a variable?
ie:  $a = "00002462"
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
ozoCommented:
$a = sprintf "%08d", 2462;
0
 
Lee5Author Commented:
$a = sprintf "%08d", 2462;
won't compile
0
 
ozoCommented:
Are you using Perl4?
What does
 perl -v
or
 print $];
tell you?
If you're still using Perl4, you'll have to write that as
 $a = sprintf("%08d", 2462);
(and you'd probably want to upgrade to Perl5)
0
 
Lee5Author Commented:
Using perl 5.003 under linux
It says I have a syntax error near $a
the prens don't help
0
 
ozoCommented:
What's the line in your program before the $a?
0
 
Lee5Author Commented:
Had problem in line before, sorry
Now it adds the 4 zeros, but it also prints them.
If I use a variable instead of the number, it compiles but prints a message saying that I can't use method "a"
0
 
ozoCommented:
please post the code which adds the 4 zeros, but also prints them,
and the code which prints a message saying that I can't use method "a"
0
 
Lee5Author Commented:
I got rid of the error but:

$b = "2462";
$a = sprintf"%08d", $b;
print "$a\n";

line 2 prints 00002462
line 3 prints it again
0
 
ozoCommented:
How do you conclude that line 2 prints 00002462?
0
 
Lee5Author Commented:
I type   ./test.cgi
If I leave out line 3, I get 00002462
If I add line 3, I get  0000246200002462

I am testing on a unix box, but will be using it on an NT box.
0
 
ozoCommented:
please post test.cgi
0
 
Lee5Author Commented:
OK I must still be asleep
I did have it in there twice
Thanks so much for your patience

Please make it an answer
0
 
Lee5Author Commented:
why is HaldorG  taking credit for ozo's answer?
0
 
Lee5Author Commented:
Sorry, I missed the name on the first box
Thanks to ozo for the help
0
 
ozoCommented:
Sorry, I must have been asleep :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.