I find very often the need to pack spaces on the left or pack with zeroes. I have used the following code so much I will probably work it into a personal library.

I, being a mere acolyte of Perl, wonder if anyone has another (better?) way to do this. Or perhaps someone has a way to streamline this approach.

sub myrpack ($$) { my($template, $charstring) = @_; $charstring = reverse $charstring; $charstring = pack $template, $charstring; $charstring = reverse $charstring; return $charstring; }

Even though you can pass in a template for the pack, I have only ever had the need for A. Another limit in this routine that has yet to bother me is you can only introduce one string for packing. You can't pack several together.

I have had the need to pack with more than one string because I've wanted to pack 0's onto a number, much like an odometer. I just pack a6a*, $zeroes, $numstring where $zeroes is just a string of zeroes longer than any of my fields. In each of these cases, I have to figure the 6 somewhere (length of field - length of $numstring).

-T


In reply to Pack'ing by Anonymous Monk

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.