I'm trying to write an interface for my team which will allow them to enter arbitrary regular expressions for purposes of search and replace. I'm having some trouble getting backreferences to work correctly in the right hand side of s///. I've tried the following bits of code:
my $var = "my dog spot"; my $expr = qr|(my dog) spot|; my $sub = qr|\1 spooge|; $var =~ s/$expr/$sub/; print $var #error: "/\1 spooge/: reference to nonexistent group"
Rats. So then I tried:
my $var = "my dog spot"; my $expr = qr|(my dog) spot|; my $sub = qr|$1 spooge|; $var =~ s/$expr/$sub/; print $var; #prints: (?-xism: spooge)
Trying to be clever doesn't work either:
my $var = "my dog spot"; my $expr = qr|(my dog) spot|; my $sub = qq|$1 spooge|; $var =~ s/$expr/qr|$sub|/e; print $var; #prints (?-xism: spooge)

And of course, the obvious method:
my $var = "my dog spot"; my $expr = qq|(my dog) spot|; my $sub = qq|\1 spooge|; #could be $1 $var =~ s/$expr/$sub/e; #prints " spooge"
How do I get it so that it prints: "my dog spooge"? Given the above example where I don't know what my matching pattern or subsitution pattern is going to be? Again, it works fine if I don't have backrefs- but backreferences are pretty critical to the work we are doing. Thanks!!! h0mee

In reply to substitution interpolation? by h0mee

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.