Substitution and Text Within Parentheses

A

Addy

Hello,

I have the following code:

$orig = '(original text)';
$subs = '(NEW TEXT)';

$foo = $orig;
$foo =~ s/$orig/$subs/;
print ("$foo\n");

The output is: ((NEW TEXT))

Why is it replacing only what is inside the parentheses, and not all
the text including the parentheses? I'm expecting the output to be:
(NEW TEXT)

What am I overlooking?

Thank you.
 
P

Peter Hickman

Addy said:
Hello,

I have the following code:

$orig = '(original text)';
$subs = '(NEW TEXT)';

$foo = $orig;
$foo =~ s/$orig/$subs/;
print ("$foo\n");

The output is: ((NEW TEXT))

Why is it replacing only what is inside the parentheses, and not all
the text including the parentheses? I'm expecting the output to be:
(NEW TEXT)

What am I overlooking?

Thank you.

The ( and ) are used for grouping in the lhs of a s///.

So $foo =~ s/$orig/$subs/;
Reads as $foo =~ s/(original text)/$subs/;

Thus only original text is matched and replaced.

This would work:

$orig = '\(original text\)';

The ( and ) have no meaning on the rhs of a s///
 
A

Anno Siegel

Addy said:
Hello,

I have the following code:

$orig = '(original text)';
$subs = '(NEW TEXT)';

$foo = $orig;
$foo =~ s/$orig/$subs/;
print ("$foo\n");

The output is: ((NEW TEXT))

Why is it replacing only what is inside the parentheses, and not all
the text including the parentheses? I'm expecting the output to be:
(NEW TEXT)

What am I overlooking?

You are overlooking that parentheses have meaning in a regex.
Substituting "(original text)" in the regex gives /(original text)/.
That is a regex that matches "original text" and captures the result
in $1. It doesn't match the parentheses. If you want that, you have
to quote them: /\(original text\)/.

Since this happens frequently with interpolated strings in a regex,
there is a special construct "\Q" to do the quoting for you:

$foo =~ s/\Q$orig/$subs/;

To see what "\Q" does exactly, look up "quotemeta()" in perldoc.
It does the same thing, but is easier to find.

Anno
 

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,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top