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

I'd like to interpolate a RHS that contains backrefs. Like this:
$lhs = '(.)oo'; $rhs = '\1ar'; s/$lhs/$rhs/; # I want to turn foo into far
(except that doesn't work.)

Replies are listed 'Best First'.
Re: How can I combine backreferences and regex interpolation?
by mdillon (Priest) on Sep 20, 2000 at 19:16 UTC
    this should work:
    $_ = 'foo'; $lhs = '(.)oo'; $rhs = '$1."ar"'; s/$lhs/$rhs/ee;
    or this:
    $_ = 'foo'; $lhs = '(.)oo'; $rhs = '${1}ar'; s/$lhs/qq{qq{$rhs}}/ee;
    p.s. '\1' is the proper way to do a backreference (which is part of the left-hand side), but it is not the right way to refer to a capture variable in the right-hand side. for that (and anywhere else outside the regular expression part of an s/// or m// expression), you're supposed to use '$1'.
RE: How can I combine backreferences and regex interpolation?
by knight (Friar) on Sep 20, 2000 at 19:25 UTC
    You can eval it:
    % cat x.pl $_ = 'foo'; $lhs = '(.)oo'; $rhs = '\1ar'; eval "s/$lhs/$rhs/"; print "$_\n"; % perl x.pl far %
Re: How can I combine backreferences and regex interpolation?
by rpc (Monk) on Sep 21, 2000 at 01:01 UTC
    if you don't mind the original value being changed: my $foo = "foo"; $foo =~ s/(.)oo/$1ar/;