I have written a quick script to allow me to process certain types of data using perl's regex search and replace. Problem is, I ask the user for the search regex and the replace regex, and the backreference variables included in the user-defined replace regex are being parsed as regualr string characters. This happens if I use the $1 or the \1 notation. I thought maybe it was some magic that was being done on the string I read in from STDIN, but I wouldn't think that would effect the \1 style notation. To illustrate the problem, here's the code:
print "Search REGEX: "; chop($search = <STDIN>); print "Replace with: "; chop($replace = <STDIN>); $text =~ m/($search)/; $test = $1; print "\n\nWith the given pattern, the first string found was:\n$test\ +n\n"; $test =~ s/$search/$replace/m; print "Which was evaluated to:\n$test\n\n"; print "Continue (y/n)?: "; chop($cont = <STDIN>); if ($cont eq 'y' || $cont eq 'Y'){ $num = $text =~ s/$search/$replace/mg; open (OUT, "> $file.out"); print OUT $text; close (OUT); print "\n\n Successfully replaced $num occurances.\n"; } else { print "Aborted.\n"; }
As you can see, this reads in the regex, then does a match on the first search result, prints out what would happen if the pattern is applied, and asks if they would like to continue. If so, it should do the rest of the matching. But if I type in, say, ^(\d{3})-(\d{3})-(\d{4}) as the search and $1$2$3 as the replace, it just replaces it with '$1$2$3' instead of the interpolated results. I've tried a few things (adding quotes, using the /e modifier on the s/// function, etc.) but all with the same results. Any ideas?

In reply to Using user input in a regex replace by rael9

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.