|
Posted by John W. Krahn on July 8, 2008, 12:42 pm
Please log in for more thread options comp.llang.perl.moderated wrote:
>> jerrykrin...@gmail.com wrote:
>>> my $s = "The sneaky cat sneaked sneakily." ;
>>> I would like a simple s/// statement which would replace only the $nth
>>> occurrence of "sneak". ($n is a variable). Can't find the answer.
>>> Is this possible?
>> With sed it's trivial. With Perl, I'd do this:
>>
>> my $x=0;my $n=3;
>>
>> while($s=~/sneak/g) {
>> if (++$x==$n) {
>> $s=~s/sneak\G/replacement/;
>
> alternatively:
>
> substr($s, $-[0], $+[0]-$-[0]) = replacement;
alternatively:
substr $s, $-[0], $+[0] - $-[0], 'replacement';
>> last;
>> }
>>
>> }
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
|