Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
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?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: s/// ignoring subexpressions with variable replacement patterns
by mattriff (Chaplain) on Oct 04, 2002 at 15:10 UTC | |
by Anonymous Monk on Oct 04, 2002 at 15:19 UTC | |
by thelenm (Vicar) on Oct 04, 2002 at 15:22 UTC | |
|
Re: s/// ignoring subexpressions with variable replacement patterns
by Joost (Canon) on Oct 04, 2002 at 15:23 UTC | |
by mattriff (Chaplain) on Oct 04, 2002 at 16:58 UTC |