I'm trying to take each line of input, run a substitution according to user-specified "before" and "after" patterns, and output the result - it's for use in a typical "Perl rename"-type script. Because the patterns are user-specified, I end up doing basically $input =~ s/$old/$new/ - however, this seems to break subexpression references on the replacement side.
Demonstration code:
#!/usr/bin/perl -w use strict; my ($oldpat, $newpat); my ($oldname, $newname); $oldname = 'foo-64-bar'; # would normally be read from stdin # basic substitution $newname = $oldname; $newname =~ s/-([0-9]+)-/_$1_/; print "static patterns: $oldname becomes $newname\n"; # the same, but with the patterns in variables $oldpat = '-([0-9]+)-'; $newpat = '_$1_'; $newname = $oldname; $newname =~ s/$oldpat/$newpat/e; print "variable patterns: $oldname becomes $newname\n";
As far as I can see, this should perform the same substitution in both cases, but it produces this:
static patterns: foo-64-bar becomes foo_64_bar variable patterns: foo-64-bar becomes foo_$1_bar
I've checked the perlop and perlre manpages, as well as any likely-looking threads here, but didn't see anything suggesting that the contents of a scalar used as a replacement pattern are somehow special, or that $var references in such a string won't be interpolated (unless you use single quotes as the pattern delimiter, which I'm not). I've tried wrapping the subsitution in an eval{}, as well as leaving off the /e modifier, but neither made any difference.
I'm sure I'm missing something obvious. Anyone care to tell me what it might be?
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |