in reply to Re^2: Interpolate into replacement with s//?
in thread Interpolate into replacement with s//?

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.

Replies are listed 'Best First'.
Re^4: Interpolate into replacement with s//?
by philkime (Beadle) on Nov 09, 2011 at 21:18 UTC
    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.

        I can't seem to work out the quoting when the string is from elsewhere:
        use 5.014000; use Config::General; my $conf = new Config::General({replace => 'Z\l$1Z'}); my $string = q/ABC/; my $search = qr/^(A)/; say $conf->{config}{replace}; my $replace = q/$conf->{config}{replace}/; $string =~ s/$search/$replace/gee; say $string;
        gives:
        Z\l$1Z Z\l$1ZBC
        I've tried all sorts of combinations of quoting and regexp flags but I can't seem to get it to work when $replace isn't explicitly assigned as in your example.