I am trying to create an all purpose string padding function. This function takes a string and the max length, then optionally the padding direction and pad character.

After looking around Q&A, Tutorials, and using the Super Search, I still haven't found any nodes addressing this.

My first thought was to use sprintf. The problem with this is that, as far as my research has shown, there is no way to specify the pad character with sprintf for strings (besides 0 instead of the default space). This of course solves most of my cases, but not entirely as generic as I would like.

My next solution is to simply append the desired characters to the string in the desired place, such as (basic idea, not a polished sub):

# this assumes that $s will never be longer than $max_length sub my_pad { my ($s, $max_length, $dir, $pad_char) = @_; $pad_char ||= ' '; $dir ||= 'L'; my $pad_string = $pad_char x ($max_length - length $s); return $s . $pad_string if $dir eq 'R'; return $pad_string . $s; }

My question is, does anyone know a more simple way of doing this? It feels like there is something very basic I'm missing, but I can't put my finger on it. Thanks in advance!


In reply to General Purpose String Padding by thedoe

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.