Passing a $1 within a scalar to a s/// doesn't work. Why?

R

Rob Campbell

Hi,

Still in the early stages of this Perl business but haven't been able to
find an answer to this question anywhere. Perhaps someone here can help.

I have a little function which takes as its inputs two regular expressions.
The first line of the function is:
my($simulate,$oldpart,$newpart,@rest) = @ARGV;

The function just uses these to perform a substitution:
$d =~ s/$oldpart/$newpart/;

The problem is that when I want to capture text in the first expression to
use it as a "$1" in the second, it don't work: the '$1' is interpretted
literally.

i.e.
if $oldpart contains 'binoise\w*(G1_[0-9]+)\.src', and and $newpart contains
'_binoise.src'; then I get, for example:
../binoise9G1_12.src -> ./_binoise.src

Not what I want, but fine, it works. However, if $newpart now contains
'$1_binoise.src' then I get:
../binoise9G1_12.src -> ./$1_binoise.src

Huh? Why is the $1 being interpreted literally. I've not done anything else
silly since if I hard-code my substitution so that it looks like this:
$d =~ s/$oldpart/$1_binoise/;
Then I get what I want:
../binoise9G1_12.src -> ./G1_12_binoise


I've tried escaping the $ in $newpart but that doesn't work either. Why does
Perl interpret my substitution command differently when I feed it a
variable compared to when I feed it the regexp directly? How do I get it to
play ball and allow a $1 to be interpretted correctly when it's passed to
my s/// command in a scalar.

Thanks!
Rob
 
G

Gunnar Hjalmarsson

Rob said:
How do I get it to play ball and allow a $1 to be interpretted
correctly when it's passed to my s/// command in a scalar.

perldoc -q "expand variables"
 
T

Tad McClellan

Jim Gibson said:
I am not quite sure why '$d =~ /$oldpart/$newpart/e;' doesn't work,


Because the replacement part is now code rather than a string.

If you instead said

$foo = $newpart;

you would expect a literal '$1' in $foo's value, as there is only
one round of evaluation and that is used to fetch the value from $newpart.

Same thing for the code above.

but
wrapping the replacement text in double quotes and forcing another
round of evaluation works:


That would be like

$foo = eval $newpart;

were you _would_ expect variables in $newpart's value to be eval()uated.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top