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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |