Take the 2-minute tour ×

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.

share|improve this question
You should ask something such as "How do I insert a certain amount of whitespaces in perl / regex?"... –  ivan_ivanovich_ivanoff Sep 30 '09 at 11:25
What is the word "regex" doing in your title? –  innaM Sep 30 '09 at 11:47
I included regex in the title (note it has since been edited for clarity) since I assume that there may be a hacky way of recursively replacing a space with say 10 spaces five times to get an order of 10000 spaces. –  Timo Oct 1 '09 at 10:19
add comment

3 Answers

up vote 24 down vote accepted

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.

share|improve this answer
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 Sep 30 '09 at 16:11
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 Sep 30 '09 at 21:17
No-one got on my case and I think your edits make sense. I was just a little concerned that someone who comes along later might wonder why I've got 20K in my code when there's no mention of it elsewhere. Just trying to keep up with the SO ethos of not just solving someone's problem, but creating a repository of useful Q&A for future readers. –  dave Sep 30 '09 at 21:48
add comment

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);
share|improve this answer
add comment

use the 'x' operator:

print ' ' x 20000;
share|improve this answer
add comment

Your Answer


