Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #214 Pad string on the right

Append extra character c at the end of string s to make sure its length is at least m.
The length is the number of characters, not the number of bytes.

$s .= $c x ($m - length $s)

String $c (one character) is repeated $m - length $s times. Perl generates an empty string if the repeat count is zero or negative. The result is appended to $s (by the .= operator, similar to +=).
$s = length($s) >= $m ? $s : $s . $c x ( $m-length($s) );

The . operator concatenates; the x operator repeats a string on the left by the count on the right. For compactness, ? : is used instead of if-else. A more idiomatic approach would avoid calling length() twice.
s = s.PadRight(m, c);

New implementation...