in reply to Re^2: Left padding a number with zeros: PerlFaq method didn't work for me.
in thread Left padding a number with zeros: PerlFaq method didn't work for me.
In the example from perlfaq:
The variable $pad_len is written as ${pad_len}. This is to ensure that it is correctly interpreted. If it wasn't written this way, it would be interpreted as $pad_lens.$padded = sprintf("%${pad_len}s", $text);
So where it says that you may use an integer in place of $pad_len, it means that it would be written as:
$padded = sprintf("%04d", $text);
Cheers,
Darren :)
Update: Actually, after re-reading this I realised that the original code snippet I gave you was incorrect. I've corrected it.
Also, it's worth pointing out that $pad_length in the above examples is a little misleading, as it actually refers to the total length of the resultant string, rather than the length of the padding. The best way to demonstrate this is by example:
#!/usr/bin/perl -w use strict; my $string1 = "12345"; # 5 character string my $string2 = "1234567890"; # 10 character string my $pad_len = 10; my $padded1 = sprintf("%${pad_len}s", $string1); my $padded2 = sprintf("%${pad_len}s", $string2); print "|$padded1|\n|$padded2|\n";
Which gives:
| 12345| |1234567890|
Note that the 2nd string isn't padded at all, because the length of the string is already >= than $pad_len.
Update: blah - you're working with numbers, not strings. Disregard the previous update, and I'll crawl back into my box :)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Left padding a number with zeros: PerlFaq method didn't work for me.
by JCHallgren (Sexton) on Jan 17, 2006 at 06:49 UTC |