in reply to How to right align outputs of stored data in a variable?
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to right align outputs of stored data in a variable?
by AnomalousMonk (Archbishop) on Feb 05, 2017 at 23:23 UTC | |
by Marshall (Canon) on Feb 06, 2017 at 00:36 UTC | |
by AnomalousMonk (Archbishop) on Feb 06, 2017 at 05:40 UTC | |
by Marshall (Canon) on Feb 07, 2017 at 20:53 UTC | |
by AnomalousMonk (Archbishop) on Feb 07, 2017 at 22:35 UTC |