I like the answer from davido. Some additional comments for you...

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

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.