Be concise.
Be useful.
All contributions dictatorially edited by webmasters to match personal tastes.
Please do not paste any copyright violating material.
Please try to avoid dependencies to third-party libraries and frameworks.
i = (m-len(s))/2
j = (m - len(s)) - (m-len(s))/2
s = repeat(c,i) // s // repeat(c,j)
while (s.length() < m) s = c + s + c;
sub center {
my ($s, $m, $c) = @_;
my $slen = length $s;
return $s if $slen > $m;
$c //= ' ';
my $r = $c x $m;
my $p = int($m/2 - $slen/2);
substr($r, $p, $slen, $s);
return $r;
}
print center("abcd",10,"X");
Create a string of length $m by repeating $c. Calculate the midpoint of $m and of $s and use that to calculate the position $s should start in $m. Use substr to substitute $s into $m. $c is optional, default to space. If the length of $s > $m then $s is returned. Using substr is ~4% faster than string concatenate, and ~13% faster than join.
s = s.center(m, c)
s = f'{s:{c}^{m}}'
s = s.center(m, c)