Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re^3: Left padding a number with zeros: PerlFaq method didn't work for me.

by McDarren (Abbot)
on Jan 17, 2006 at 04:46 UTC ( [id://523667]=note: print w/replies, xml ) Need Help??


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.

Ah, okay - I think I see where you may have got confused.

In the example from perlfaq:

$padded = sprintf("%${pad_len}s", $text);
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.

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
    Ok...thanks to those who replied and explained why my syntax was warped! Now I feel a bit better! Given that I have a total of maybe 2 weeks (and 3 pgrms) using Perl, at best, y'all may thus understand why I read it the way I did...

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2024-04-16 11:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found