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 :)


In reply to Re^3: Left padding a number with zeros: PerlFaq method didn't work for me. by McDarren
in thread Left padding a number with zeros: PerlFaq method didn't work for me. by JCHallgren

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.