The printf() "format spec" reserves a minimum field width. In some cases that minimum width will be exceeded to print what is necessary.
When there are multiple variables, I always put an explicit space in the format spec to guarantee that the printout will have a space between columns. If you have a 5 digit integer, do not use %6d and count on that leading column to be blank. Use " %5d". If 8 digits show up for the integer, they will get printed and perhaps more importantly a space will separate that column from the previous one. Here are some examples:
#!/usr/bin/perl use strict; use warnings; my $x = "a_long_string"; print "*using a single field:\n"; printf "%3s\n","a"; printf "%3s\n","abc"; printf "%3s\n",$x; print "\n*using format with 2 fields:\n"; printf "%3s%4s\n", "abc", "a"; printf "%3s%4s\n", "abc", "abcd"; printf "%3s%4s\n", $x, "abcd"; printf "%3d%3d\n", 123, 456; # # better, use a explict space between format fields # print "\n*using explict space between 2 fields\n"; printf "%3s %4s\n", $x, "abcd"; printf "%3d %3d\n", 123789, 456; __END__ *using a single field: a abc a_long_string *using format with 2 fields: abc a abcabcd a_long_stringabcd 123456 *using explict space between 2 fields a_long_string abcd 123789 456
In reply to Re: How to right align outputs of stored data in a variable?
by Marshall
in thread How to right align outputs of stored data in a variable?
by perlnovice1900
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |