http://www.perlmonks.org?node_id=735481


in reply to Bug in substitution operator?

Interesting. It does sound buggy.

And it does the same thing with brackets too, notice. Simpler example:

@s = ("foo bar baz") x 4; $bar = "rab"; %bar = (1 => "eek"); @bar = (undef, 'oof'); $s[0] =~ s{(bar)} {$bar\{1\}}; $s[1] =~ s{(bar)} [$bar\{1\}]; $s[2] =~ s{(bar)} {$bar\[1\]}; $s[3] =~ s{(bar)} [$bar\[1\]]; for $i (0..3) { print "$i -> '$s[$i]'\n"; }

Yields

0 -> 'foo eek baz' 1 -> 'foo rab{1} baz' 2 -> 'foo rab[1] baz' 3 -> 'foo oof baz'

(5.8 here)

So something about having the delimiter be the same as your subscripting character makes it real hard to escape.

For extra fun, notice that using two \'s in the sub fails as "replacement not terminated", and using 3 leaves one sitting in your string:

4 -> 'foo rab\[1] baz'

So it doesn't seem like you can all that easily work around it except by changing the delimiters. Maybe playing with escaping... yes, that seems to work:

$s[4] =~ s{(bar)} [$bar\E\[1\]]; 4 -> 'foo rab[1] baz'

Wackiness.