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

Hi,

This is a sample code that works:
$content =~ s/my (mom)/our \1/;
Now look it (does not work):
my $from = "my (mom)"; my $to = "our \\1"; $content =~ s/$from/$to/;
How can I resolve it?

Thanks, Fabio

Edited by Chady -- added code tags.

Replies are listed 'Best First'.
Re: Advanced (or not) regular expression
by japhy (Canon) on Apr 23, 2004 at 02:00 UTC
    First, you should be using $1 on the right-hand side, not \1.

    Second, you need to be trickier. Here's one way:

    my $from = "my (mom)"; # UPDATE: was '"my (mom")' my $to = "our \$1"; $content =~ s/$from/qq{qq{$to}}/ee;
    It's a bit difficult to explain, but it's two layers of evaluation. The first layer turns qq{qq{$to}} into qq{our $1}, and the second layer interpolates $1.

    Or, you could use DynScalar:

    use DynScalar; my $from = "my (mom)"; my $to = dynamic { "our $1" }; $content =~ s/$from/$to/;
    It's magic.
    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;
      Hmm, that first chunk of code won't compile. Here is an alternative solution:
      use strict; use warnings; my $content = "my mom"; my $from = qr|my (mom)|; my $to = '"our ".$1'; $content =~ s/$from/$to/ee; print "$content\n";

      -Mark