perlfaq4: How do I pad a string with blanks or pad a number with zeroes?

[email protected] (_brian_d_foy)
Newsgroups perl.perlfaq.workers,perl.documentation
Message-ID <180120031417149694%[email protected]>
* added examples that use the * conversion in sprintf


Index: perlfaq4.pod
===================================================================
RCS file: /cvs/public/perlfaq/perlfaq4.pod,v
retrieving revision 1.39
diff -u -d -r1.39 perlfaq4.pod
--- perlfaq4.pod        3 Jan 2003 20:06:21 -0000       1.39
+++ perlfaq4.pod        18 Jan 2003 20:15:58 -0000
@@ -811,9 +811,6 @@
 
 =head2 How do I pad a string with blanks or pad a number with zeroes?
 
-(This answer contributed by Uri Guttman, with kibitzing from
-Bart Lateur.)
-
 In the following examples, C<$pad_len> is the length to which you wish
 to pad the string, C<$text> or C<$num> contains the string to be
padded,
 and C<$pad_char> contains the padding character. You can use a single
@@ -828,13 +825,16 @@
 C<$pad_len>.
 
     # Left padding a string with blanks (no truncation):
-    $padded = sprintf("%${pad_len}s", $text);
+       $padded = sprintf("%${pad_len}s", $text);
+       $padded = sprintf("%*s", $pad_len, $text);  # same thing
 
     # Right padding a string with blanks (no truncation):
-    $padded = sprintf("%-${pad_len}s", $text);
-
+       $padded = sprintf("%-${pad_len}s", $text);
+       $padded = sprintf("%-*s", $pad_len, $text); # same thing
+
     # Left padding a number with 0 (no truncation):
-    $padded = sprintf("%0${pad_len}d", $num);
+       $padded = sprintf("%0${pad_len}d", $num);
+       $padded = sprintf("%0*d", $pad_len, $num); # same thing
 
     # Right padding a string with blanks using pack (will truncate):
     $padded = pack("A$pad_len",$text);

-- 
brian d foy, [email protected]
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.