Logo

Programming-Idioms

History of Idiom 216 > diff from v6 to v7

Edit summary for version 7 by Corion:
New Perl implementation by user [Corion]

Version 6

2020-04-15, 21:31:38

Version 7

2020-04-29, 09:48:03

Idiom #216 Pad a string in the center

Prepend extra character c at the beginning and ending of string s to make sure its length is at least m.
After the padding the original content of s should be at the center of the result.
The length is the number of characters, not the number of bytes.

E.g. with s="abcd", m=10 and c="X" the result should be "XXXabcdXXX".

Idiom #216 Pad a string in the center

Prepend extra character c at the beginning and ending of string s to make sure its length is at least m.
After the padding the original content of s should be at the center of the result.
The length is the number of characters, not the number of bytes.

E.g. with s="abcd", m=10 and c="X" the result should be "XXXabcdXXX".

Imports
use feature 'signatures';
Code
my $s = 'abcdefghijk';
my $m = 10;
print center_pad( $s, $m, "X" );

sub center_pad( $s, $m, $c=" " ) {
    my $total_padding = $m-length($s);

    if( $total_padding ) {
        my $l = int($total_padding/2);
        my $r = $total_padding-$l;
        return join "", ($c x $l), $s, ($c x $r);
    } else {
        return $s
    }
}