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:
Hope this helps, larryk$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";
In reply to Re: Re^2: Regex Grumblings (Variable Interpolation)
by larryk
in thread Regex Grumblings (Variable Interpolation)
by tadman
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |