tags:

views:

2058

answers:

3

I am learning Perl, so please bear with me for this noob question.

How do I repeat a character n times in a string?

I want to do something like below:

$numOfChar = 10;

s/^\s*(.*)/' ' x $numOfChar$1/;
+1  A: 

You're right. Perl's x operator repeats a string a number of times.

print "test\n" x 10; # prints 10 lines of "test"

EDIT: To do this inside a regular expression, it would probably be best (a.k.a. most maintainer friendly) to just assign the value to another variable.

my $spaces = " " x 10;
s/^\s*(.*)/$spaces$1/;

There are ways to do it without an extra variable, but it's just my $0.02 that it'll be easier to maintain if you do it this way.

EDIT: I fixed my regex. Sorry I didn't read it right the first time.

Chris Lutz
That didn't work. I think it works only inside print statement
chappar
For me it works with perl 5.10.0
tstenner
I am trying something like this. s/^(.*)/'p' x $numOfChar/; I have modified my question
chappar
+10  A: 

Your regular expression can be written as:

$numOfChar = 10;

s/^(.*)/(' ' x $numOfChar).$1/e;

but - you can do it with:

s/^/' ' x $numOfChar/e;

Or without using regexps at all:

$_ = ( ' ' x $numOfChar ) . $_;
depesz
Note that this answer no longer applies, because chappar added a \s* to his question after this answer was given.
ysth
At the moment none of the answers really apply.But it can be easily fixed.Just change: s/^/' ' x $numOfChar/e;into: s/^\s*/' ' x $numOfChar/e;
depesz
+9  A: 

By default, substitutions take a string as the part to substitute. To execute code in the substitution process you have to use the e flag.

$numOfChar = 10;

s/^(.*)/' ' x $numOfChar . $1/e;

This will add $numOfChar space to the start of your text. To do it for every line in the text either use the -p flag (for quick, one-line processing):

cat foo.txt | perl -p -e "$n = 10; s/^(.*)/' ' x $n . $1/e/" > bar.txt

or if it's a part of a larger script use the -g and -m flags (-g for global, i.e. repeated substitution and -m to make ^ match at the start of each line):

$n = 10;
$text =~ s/^(.*)/' ' x $n . $1/mge;
kixx