You are right, Perl's regexes do undergo variable interpolation but it's only done once, e.g. $bar becomes the value it holds and $foo becomes $bar which doesn't then become $bar's value.

The reason why neither of your bits of code work (assuming you are using the same $_ value for both) is because as $foo is interpolated to $bar the regex becomes s/$bar/BAR/g which is $ (the end of line) followed by the characters 'bar'.

I expect there is a way to fiddle with the end of line character and then do a s/$foo/BAR/m #treat string as multi-line (or maybe it's s/$foo/BAR/s # treat string as single-line - I can never remember) to get it to match your $_ if you took the $ out (ie. if the \b before 'bar' somehow became an end of line) but I'll have to open that one up as it's over my head. (where's japhy when we need him?)

The reason \Q$foo\E works is because after $foo is interpolated to $bar the \Q\E slaps a \ in front of the $ so it is treated literally rather than as the end-of-line marker.

You will find that your second lot of code will work if you do:

$foo = '\$bar'; # put the backslash in yourself $bar = 'snafu'; $_ = 'I am certain that the value of $bar is "snafu".'; print $_,"\n"; s/$foo/BAR/g; print $_,"\n";
Hope this helps, larryk

In reply to Re: Re^2: Regex Grumblings (Variable Interpolation) by larryk
in thread Regex Grumblings (Variable Interpolation) by tadman

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.