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

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?

Replies are listed 'Best First'.
Re: Using user input in a regex replace
by Tanktalus (Canon) on May 10, 2006 at 21:33 UTC