in reply to $1 in variable regex replacement string

The reason it doesn't work is (of course) found in the Camel Book:
The right side of the substitution (between the second and third slashes) is mostly a funny kind of double-quoted string, which is why you can interpolate variables there, including backreference variables. (p.41)

As you know you only get one level of interpolation in Perl, i.e. your $repl gets replaced by whatever its value is at that moment and then interpolation stops and hands the regex to the regex-engine, which will find a literal $1 and not the value inside the backreference variable $1 you wished for.

The only solution is through the /e modifier als already pointed out.

CountZero

"If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

  • Comment on Re: $1 in variable regex replacement string

Replies are listed 'Best First'.
Re: Re: $1 in variable regex replacement string
by dvergin (Monsignor) on Feb 12, 2003 at 20:35 UTC
    So I pose roughly the same question here that I posed to tadman -- if I go the /e or /ee route, what are the things that $repl might contain that could potentially do horrible things.

    If I filter out '(?{...})' constructs, is that enough? If so, this solution is do-able.

      Really bad thing could happen even outside '(?{...})' constructs.

      For example (this is something totally innocent, but you get the idea):

      use strict; my $str = 'abcadefaghi'; my $pat = qr/(a.)/; my $repl = 'system dir '; $str =~ s/$pat/$repl/eeg;

      Of course you could try to filter out all system, exec and backticks, but that is only solving a small part of the possible problems as anything inside the $repl-variable gets run as a perl-program.

      CountZero

      "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law