philkime has asked for the wisdom of the Perl Monks concerning the following question:

I need to pass in from a config file, a regexp and replacement for s// but can't seem to work out how to allow $1, $2 in the replacement:
$string = 'ABC'; $search = qr/^(A)/; $replace = '$1Z'; $string = s/$search/$replace/g; say $string;
I would like to see "AZBC", for example but the $1 is interpreted as literal, as I suppose I should expect. Is there some way to have the replacement interpret $1, $2 etc?

Replies are listed 'Best First'.
Re^2: Interpolate into replacement with s//?
by ikegami (Patriarch) on Nov 09, 2011 at 20:43 UTC

    $replace contains a template. Therefore, you need a template engine to process it. The only existing template module I know that can process that language is String::Interpolate. (Yeah, it has a weird interface.)

    Alternatively, if $replace actually contained a string literal (i.e. Perl code), you could use eval to evaluate it.

    $string = 'ABC'; $search = qr/^(A)/; $replace = '"$1Z"'; $string = s{$search}{ my $replacement = eval($replace); die $@ if $@; $replacement }eg; say $string;
      ikegami wrote:
      $replace contains a template. Therefore, you need a template engine to process it.
      Aw /gee whiz, we don’t need no stinkin’ modules for such a trivial task. Merely render unto Perl that which is Perl’s:
      use v5.14; my $string = q/ABC/; my $search = qr/^(A)/; my $replace = q/"Z\l$1Z"/; $string =~ s/$search/$replace/gee; say $string;
      Which when run duly prints out ZaZBC.
        Hmm, I tried /gee but $replace isn't directly assigned, it's from elsewhere so say I'd read $replace from another file and it was a string 'Z$1Z' then this doesn't seem to work?
Re: Interpolate into replacement with s//?
by SuicideJunkie (Vicar) on Nov 09, 2011 at 20:40 UTC

    It was a little hard to find, but this may be what you want:

    perlretut Says:
    A modifier available specifically to search and replace is the s///e evaluation modifier. s///e treats the replacement text as Perl code, rather than a double-quoted string. The value that the code returns is substituted for the matched substring. s///e is useful if you need to do a bit of computation in the process of replacing text. This example counts character frequencies in a line: