Yida Yuan
Yida Yuan

Reputation: 25

How to replace matched pattern in perl

I'm trying to write a Perl program that accepts an input pattern and print the string with the matched part enclosed with parentheses. For example, if I input the regex ".p" and the string is "developing", it should print "devel(op)ing"

Here is my program:

if (/($pattern)/) {
    $_ =~ s/$1/($1)/;
    print;
} else {
    print "no match\n";
}

When I run it, I got the error message:

Use of uninitialized value $1 in concatenation (.) or string at q1.pl line 12, <> line 1.

The string "devel()ing" was returned. I did some research and seems like the $1 is uninitialized because the string is not matched, but in my case, the $1 should always be initialized since I checked with "if...else..."

Upvotes: 1

Views: 5031

Answers (2)

Barmar
Barmar

Reputation: 782488

$1 in a replacement contains the first capture group in the match, but there are no capture groups in your regular expression. You can use $& to get everything matched by the regular expression.

s/$1/($&)/;

Upvotes: 3

choroba
choroba

Reputation: 242323

After the match, $1 contains the string op.

The substitution than matches the op, but there are no parentheses in the search part, so $1 gets cleared, and there's nothing to substitute the op with.

Add the parentheses to create the capture group again:

s/($1)/($1)/;

Upvotes: 1

Related Questions