Perlfunc: padtext()

Simply function to left, right, or center align text in perl. Just copying the python string methods.

sub padtext {
    my ($text, $len, $align, $ret) = @_;
    $align = lc(substr($align,0,1));

    if ($align eq "r") { # Right
        $ret = (" " x ($len - length($text))) . $text;
    } elsif ($align eq "c" || $align eq "m") { # Center/Middle
        my $half = int(($len - length($text)) / 2);
        my $left = my $right = " " x $half;
        if ($half * 2 + length($text) != $len) { $left .= " "; }

        $ret = $left . $text . $right;
    } else { # Left
        $ret = $text . (" " x ($len - length($text)));
    }

    return $ret;
}
Leave A Reply
All content licensed under the Creative Commons License