$n =~ s/(^| )$a( |$)/$1$b$2/i;
You can avoid the $1..$2 in the substitution if you can avoid capturing the spaces, which you can do by matching with lookahead/lookbehind: $n =~ s/(^|(?<= ))$a((?= )|$))/$b/i;
Or inverse the sense of the lookarounds: "not after a non-space" rather than "after a space, or after nothing": $n =~ s/(?<![^ ])$a(?![%a])/$b/i;
Note that the first version is adequate for most purposes, but may trip you up if you want to do a global substitution for all copies of $a: "FOO foo" =~ s/(^| )foo( |$)/${1}bar$2/ig
.. will catch the 'FOO' but not the 'foo', because having used the space as part of the first match the regexp engine will start trying to perform a second match starting at the 'f'.
The other two version do not suffer from that problem, since the lookarounds don't affect where a future match will start.
Hugo |