How do I pad a string with blanks or pad a number with zeroes?

(This answer contributed by Uri Guttman, with kibitzing from Bart Lateur.)

In the following examples, $pad_len is the length to which you wish to pad the string, $text or $num contains the string to be padded, and $pad_char contains the padding character. You can use a single character string constant instead of the $pad_char variable if you know what it is in advance. And in the same way you can use an integer in place of $pad_len if you know the pad length in advance.

The simplest method uses the sprintf function. It can pad on the left or right with blanks and on the left with zeroes and it will not truncate the result. The pack function can only pad strings on the right with blanks and it will truncate the result to a maximum length of $pad_len.

    # Left padding a string with blanks (no truncation):
    $padded = sprintf("%${pad_len}s", $text);
    # Right padding a string with blanks (no truncation):
    $padded = sprintf("%-${pad_len}s", $text);
    # Left padding a number with 0 (no truncation): 
    $padded = sprintf("%0${pad_len}d", $num);
    # Right padding a string with blanks using pack (will truncate):
    $padded = pack("A$pad_len",$text);
If you need to pad with a character other than blank or zero you can use one of the following methods. They all generate a pad string with the x operator and combine that with $text. These methods do not truncate $text.

Left and right padding with any character, creating a new string:

    $padded = $pad_char x ( $pad_len - length( $text ) ) . $text;
    $padded = $text . $pad_char x ( $pad_len - length( $text ) );
Left and right padding with any character, modifying $text directly:

    substr( $text, 0, 0 ) = $pad_char x ( $pad_len - length( $text ) );
    $text .= $pad_char x ( $pad_len - length( $text ) );

Back to perlfaq4