thedoe has asked for the wisdom of the Perl Monks concerning the following question:
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!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: General Purpose String Padding
by ikegami (Patriarch) on Feb 01, 2006 at 21:12 UTC | |
|
Re: General Purpose String Padding
by saintmike (Vicar) on Feb 01, 2006 at 20:48 UTC | |
by GrandFather (Saint) on Feb 01, 2006 at 21:00 UTC | |
by thedoe (Monk) on Feb 01, 2006 at 21:01 UTC | |
by ikegami (Patriarch) on Feb 01, 2006 at 21:19 UTC | |
|
Re: General Purpose String Padding
by diotalevi (Canon) on Feb 01, 2006 at 21:47 UTC | |
|
Re: General Purpose String Padding
by Fletch (Bishop) on Feb 01, 2006 at 20:59 UTC | |
by jdporter (Paladin) on Feb 01, 2006 at 21:39 UTC | |
|
Re: General Purpose String Padding
by holli (Abbot) on Feb 01, 2006 at 21:55 UTC | |
by Anonymous Monk on Jun 27, 2015 at 20:19 UTC | |
|
Re: General Purpose String Padding
by superfrink (Curate) on Feb 01, 2006 at 23:20 UTC |