in reply to Does s/\Q$find\E/$replace/g really a plain string replace ?
Sometimes, it's just easier to try it out:
$_ = 'foo bah bar'; $find = 'bah'; $replace = '[\1]'; s/(\Q$find\E)/$replace/g; $\ = "\n"; print; # "foo [\1] bar" and not "foo [bah] bar"
But there is indeed a (more efficient?) way:
$_ = 'foo bah bar'; $find = 'bah'; $replace = '[\1]'; $idx = index($_, $find); substr($_, $idx, length($find), $replace) if $idx >= 0; $\ = "\n"; print;
Update: Here's a version that does mutliple matches:
$_ = 'foo bah bah bar'; $find = 'bah'; $replace = '[\1]'; $idx = length($_); while (($idx = rindex($_, $find, $idx-1)) >= 0) { substr($_, $idx, length($find), $replace); } $\ = "\n"; print;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Does s/\Q$find\E/$replace/g really a plain string replace ?
by diotalevi (Canon) on Oct 02, 2004 at 16:23 UTC | |
by ikegami (Patriarch) on Oct 02, 2004 at 16:32 UTC | |
|
Re^2: Does s/\Q$find\E/$replace/g really a plain string replace ?
by !1 (Hermit) on Oct 02, 2004 at 21:57 UTC |