As a workaround for this problem, Perl 5.10.0 introduces ${^PREMATCH} , ${^MATCH} and ${^POSTMATCH} , which are equivalent to $` , $& and $' , except that they are only guaranteed to be defined after a successful match that was executed with the /p (preserve) modifier.
Update: The problem you have documented is a bug in releases prior to 5.18.See Re: ${^MATCH} sometimes fails in target of substitution?.
Before 5.18 it appears that ${^MATCH} may only be available AFTER the match/replace. Adding print $(^MATCH} to your both example prints 'bcd' e.g.
perl -e '$x = "abcde"; $x =~ s/b../==${^MATCH}==/p; prin +t "$x Match:${^MATCH}\n"' a====e Match:bcd perl -e '$x = "abcde"; $sub="b.."; $x =~ s/$sub/==${^MATCH}==/p; print + "$x Match:${^MATCH}\n"' a==bcd==e Match:bcd
In reply to Re: ${^MATCH} sometimes fails in target of substitution?
by space_monk
in thread ${^MATCH} sometimes fails in target of substitution?
by raygun
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |