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

my $s = "foo bar quux";
my $pattern = q(foo (.*?) quux);
my $rep = q(foo quux $1);
$s =~ s|$pattern|$rep}|;
print "$s\n";
I would like for this to print
foo quux bar
But instead I get
foo quux $1
How can I get the substitution operator to expand the $1 embedded in the replacement variable?

Replies are listed 'Best First'.
Re: Back substitution expansion
by japhy (Canon) on Aug 20, 2001 at 03:52 UTC
    You'll need to go through a bit of effort:
    s/$pattern/qq[qq[$rep]]/ee;

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: Back substitution expansion
by Monky Python (Scribe) on Aug 20, 2001 at 11:15 UTC
    japhy already found the solution..

    The perlop manpage tells you a little more about the /e option:

    A /e will cause the replacement portion to be treated as a full-fledged Perl expression and evaluated right then and there. It is, however, syntax checked at compile-time. A second e modifier will cause the replacement portion to be evaled before being run as a Perl expression.

    MP