in reply to Re: Does s/\Q$find\E/$replace/g really a plain string replace ?
in thread Does s/\Q$find\E/$replace/g really a plain string replace ?

Good job.

You forgot to accomodate the /g on the regexp. I'd prefer to write this as a s///g but here's your version, reconstituted for the /g feature.

while ( ( my $index = index substr( $_, pos() ), $find), $index != -1 ) { substr $_, $index, length $find, $replace; pos() = $index + length $find; }
while ( ( my $index = index $_, $find), $index != -1 ) { substr $_, $index, length $find, $replace; }

Replies are listed 'Best First'.
Re^3: Does s/\Q$find\E/$replace/g really a plain string replace ?
by ikegami (Patriarch) on Oct 02, 2004 at 16:32 UTC

    At the same time you were writting that, I was writting my own /g! Mine doesn't have an infinite loop like yours does, however. Try yours with:

    $_ = 'foo bah bar'; $find = 'bah'; $replace = '[bah]'; first time in loop: foo [bah] bar second time in loop: foo [[bah]] bar third time in loop: foo [[[bah]]] bar ...