in reply to Re^2: simple regular expression
in thread simple regular expression

With nested regex evaluations like m//ee s///ee, you have to be very clear about what expression you are operating on at each stage of /e-valuation. It's best to work backwards.

In your latest example, and working backwards from the regex replacement field, the expression $outpattern, which was defined with single- (i.e., non-interpolating) quotes, evaluates to the string '$patternreadfromfile', literally. (The single-quotes are not part of the string.) Evaluating again (the second e in the /gee), the expression $patternreadfromfile evaluates to the string '-- FOUND $1 --'. This string is what is substituted into the original string.

It's as if you just need one more level of double-quotish interpolation to get what you want!

If the first evaluation yielded the string 'qq{-- FOUND $1 -- }', you could evaluate that a second time as an expression to get what you want. So $outpattern could be defined as qq{ qq{$patternreadfromfile} } and you're home and dry!

I hope this rather involved and, I hope, not too incoherent explanation will be helpful.

(BTW -- I assume the multiple levels of string definition and interpolation are needed in the final application. In your second code example as it stands, they are not; $patternreadfromfile could be interpolated more directly.)

use warnings; use strict; my $text= "start \\chapter{hello}\n end\n"; my $patternreadfromfile= "-- FOUND \$1 -- "; my $inpattern = qr/\\chapter\{(.*)\}/; # my $outpattern = q{$patternreadfromfile}; # # $outpattern eq '$patternreadfromfile' # # outputs: 'start -- FOUND $1 --\n end' my $outpattern = qq{ qq{$patternreadfromfile} }; # $outpattern eq 'qq{-- FOUND $1 -- }' # eval($outpattern) eq '-- FOUND capture_group_1_contents -- ' # outputs: what you want (i think) $text =~ s/$inpattern/$outpattern/gee; print "$text\n";

Update:

  1. ... $patternreadfromfile could be interpolated more directly.
    What I had in mind was that the pattern could be interpolated in just one evaluation step. On further consideration, I don't think this can be done. (But see graff's note below on an approach not involving s///e substitution replacement evaluation.)
  2. 2017 Feb 18: Just noticed that I was trying to apply an /e modifier to a m// match in the first paragraph above. Don't know where that came from. Fixed.