Alex Broitman
Alex Broitman

Reputation: 136

How to concatenate $1 with number in a regex

I would like to insert the number between two patterns:

$s = 'id="" value="div"';
$s =~ s/(id=")(".*)/$1123$2/;

Of course I got the error and " value="div" as a result. The expected result is id="123" value="div".

In the replacement I meant $1, then number 123 and then $2, but not $1123 and then $2. What is the correct replacement in the regex? I would like to do it in one single regex.

Thanks.

Upvotes: 7

Views: 3899

Answers (2)

Igor Chubin
Igor Chubin

Reputation: 64573

Another variant:

$s =~ s/(id=")(".*)/$1."123".$2/e;

Usage example:

$ cat 1.pl
$s = 'id="" value="div"';
$s =~ s/(id=")(".*)/$1."123".$2/e;
print $s,"\n";

$ perl 1.pl
id="123" value="div"

Upvotes: 1

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74252

$s =~ s/(id=")(".*)/$1123$2/;  # Use of uninitialized value $1123 in concatenation (.) or string

Though you expected it to substitute for $1, perl sees it as the variable $1123. Perl has no way to know that you meant $1. So you need to limit the variablisation to $1 by specifying it as ${1}:

$s =~ s/(id=")(".*)/${1}123$2/;

It is always a good idea to include the following at the top of your scripts. They will save you a lot of time and effort.

use strict;
use warnings;

For example, running your script with the above modules included results in the error message:

Use of uninitialized value $1123 in concatenation (.) or string at /tmp/test.pl line 7.

(Disregard the reported script name and line numbers.) It clearly states what perl expected.

Another approach using look-behind and look-ahead assertions:

$s =~ s/(?<=id=")(?=")/123/;

Upvotes: 17

Related Questions