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?


In reply to s/// ignoring subexpressions with variable replacement patterns by Anonymous Monk

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.