views:

396

answers:

3

I need to buff out a line of text with a varying but large number of whitespace. I can figure out a janky way of doing a loop and adding whitespace to $foo, then splicing that into the text, but it is not an elegant solution.

+18  A: 

I need a little more info. Are you just appending to some text or do you need to insert it?

Either way, one easy way to get repetition is perl's 'x' operator, eg.

" " x 20000

will give you 20K spaces.

If have an existing string ($s say) and you want to pad it out to 20K, try

$s .= (" " x (20000 - length($s)))

BTW, Perl has an extensive set of operators - well worth studying if you're serious about the language.

UPDATE: The question as originally asked (it has since been edited) asked about 20K spaces, not a "lot of whitespace", hence the 20K in my answer.

dave
Thank you, this works perfectly. I was confident that perl would have an elegant solution for doing this but my googling skills let me down (although I did find that site you mention).
Timo
I edited it to make it more generally useful. "20000" still qualifies as "a lot" in my opinion. Sorry if someone got on your case for that.
Chris Lutz
dave
+2  A: 

use the 'x' operator:

print ' ' x 20000;
dalloliogm
+8  A: 

If you always want the string to be a certain length you can use sprintf:

For example, to pad out $var with white space so it 20,000 characters long use:

$var = sprintf("%-20000s",$var);
Dave Webb