Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 220
  • Last Modified:

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?
0
Lee5
Asked:
Lee5
  • 9
  • 8
1 Solution
 
ozoCommented:
printf"%08d",2462;
0
 
Lee5Author Commented:
That prints the number but how do I make it into a variable?
ie:  $a = "00002462"
0
 
ozoCommented:
$a = sprintf "%08d", 2462;
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
HalldorGCommented:
$myvar=sprintf("%08d",2345);
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

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 9
  • 8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now