jimt has asked for the wisdom of the Perl Monks concerning the following question:

Is there a clever way to right pad a string with zeros? Left padding with zeros is, of course, easy:

sprintf("%010s", $string)
Right padding with spaces is, of course, easy:

sprintf("%-10s", $string>
But is there an equally easy way to right pad with zeros? Currently, I've come up with three ways to do it:

$padded = sprintf("%-10s", $string); #or use pack "A10" $padded = s/( +)$/"0" x length $1/e;

And:

$padded = reverse sprintf("%010s", scalar reverse $string);

And, finally:
$padded = "0" x 10; substr($padded, 0, length $string) = $string;

They all work, but they just seem...hack-ish to me. I may just be being picky, since I can easily left or right pad with spaces to my heart's content, I'd like to easily left or right pad with zeros to my heart's content too.

So is there a better/cleaner/cleverer way to right-pad with zeroes or is this it?

Replies are listed 'Best First'.
Re: clever zero _right_ pad?
by tye (Sage) on Sep 15, 2000 at 20:40 UTC
    $padded= substr($str."0"x10,0,10);

    Update: Added "$padded=" for clarity.

    Update 2: I learned this here at the Monastery from chip.

            - tye (but my friends call me "Tye")
Re (tilly) 1: clever zero _right_ pad?
by tilly (Archbishop) on Sep 15, 2000 at 21:08 UTC
    This is twisted (sorry - couldn't resist the pun) but:
    scalar reverse sprintf("%010s", scalar reverse $string);
    should do it.
Re: clever zero _right_ pad?
by jimt (Chaplain) on Sep 15, 2000 at 20:47 UTC
    Update: I did want to point out that the method using the regex to change the zeroes to the space assumes that your padded data didn't contain spaces at the end of the strings. For what we were padding, that was perfectly fine, but it may not be for you. So use that method with caution. :)

    Oh, and one more approach:
    $padded = $string . ("0" x (10 - length $string));
Re: clever zero _right_ pad?
by Fastolfe (Vicar) on Sep 15, 2000 at 20:41 UTC
    You can try this:
    $var = "0" x 10; $string = "test"; substr($var, -length($string)) = $string;
    But that's not much different than what you had.

    Oops: You said right, not left. Nevermind.

Re: clever zero _right_ pad?
by fundflow (Chaplain) on Sep 15, 2000 at 20:49 UTC
    There is no such thing as"padding by zero" from the right.

    Since you want to print a different number, might as well compute it with something like:

    $new=$val * 10**(10-int(log($val)/log(10)));
    Hmmm.. now that i look again, you wanted it for strings. tye++!