Take the 2-minute tour ×  How can I search and replace a match
with specific number of times using s///;. For example:   I want
to replace a with i in $string n times. How can I do that? n is
an integer provided by user.  share|improve this question
Answers to this question are also being provided at another
forum: perlmonks.org/?node_id=820332 –  toolic Jan 29 '10 at
13:52 Can you explain a bit more about what you are doing? You
have a bit of an XY problem here. Tell use the real problem you
are trying to solve instead of the potential solution you think
is the answer. :) –  brian d foy Jan 29 '10 at 20:16  6 Answers
6  The simple answer probably doesn't do want you want.  my $str
= 'aaaa'; $str =~ s/a/a_/ for 1..2; print $str, "\n"; # a__aaa.
But you want a_a_aa, right?  You need to count the replacements
yourself, and act accordingly:  $str = 'aaaa'; my $n = 0; $str
=~ s/(a)/ ++$n > 2 ? $1 : 'a_' /ge; print $str, "\n";  See the
FAQ, How do I change the Nth occurrence of something? for
related examples.  sh