I was recently trying to pass the $1 name to a search and replace as part of the value of another variable.

Example:
$search = "(.*)\d\d\d\d\d\d.txt";
# $search should match to some_string200912.txt
$replace = "some_value_$1";

$to_modify = "some_string200912.txt";

$to_modify =~ s/$replace/$search/g;

If I do:
print $1; # This contains the characters captured in the parantheses (some_string)

But the value of $to_modify is just "some_value_" where I would be hoping for "some_value_some_string"

The search and replace strings are being fed to the script through a delimited config file that is used to assign variables.

I worked around it but found it peculiar. Right now I'm thinking that the value of $1 in the variable value ($replace) is that at the time in which the variable was initialized and thus was empty and that THAT $1 does not get re-initialized to the value in the parantheses at the time that the regex search and replace is run. Does that sound right or is there something else going on?

Thanks for any feedback. BTW using perl 5.8.8 on HP-UX 11.1

In reply to Passing $1 as part of a variable value to a regex search and replace by zow

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.