I took jlongino's suggestion and reworked it a little bit. I moved the padding into a subroutine and made it so it only creates enough extra whitespace to satisfy the format condition.
$c = "test test test"; $c = correct_length($c); $fmt = "A4 x1 A4 x1 A4 x1 A4"; @c = unpack($fmt, "$c"); print join ("*",@c), "\n"; $d = "test test test "; $d = correct_length($d); $fmt = "A4 x1 A4 x1 A4 x1 A4"; @d = unpack($fmt, "$d"); print join ("*",@d), "\n"; sub correct_length { my ($string) = shift; $string .= ' ' unless length($string) >= 15; return($string); }
This is assuming all your widths are the same, otherwise you would want to either pass the required width as an argument to the sub (not a good idea if you use the size in multiple places) or create a hash with values and there corresponding lengths and pass the item_name. I think this would give it a little more durability. Some thing like this:
my %formats = ( "item_name" => 15, # where 15 is the length "item_name2" => 20, # etc. ); # code removed for demonstration $c = correct_length($c,'item_name'); sub correct_length { my ($string,$item) = @_; $string .= ' ' unless length($string) >= $formats{$item}; return($string); }
Then the subroutine above could be passed the item_name and the string so the only place you would have to modify length would be in the formats hash, but I don't know if your data is that complex/varied.

In reply to Re: Unpack/format by trs80
in thread Unpack/format by Reverend Phil

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.