in reply to Interpolate into replacement with s//?

$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;

Replies are listed 'Best First'.
Re^3: Interpolate into replacement with s//?
by tchrist (Pilgrim) on Nov 09, 2011 at 20:54 UTC
    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?

        It doesn't matter where the string came from. Notice he changed Z$1Z (not Perl code) to "Z$1Z" (Perl code). So you'd need to either change the file or add quotes to what you read from the file.