How to associate $ 1 with a regular expression number

I would like to insert a number between two patterns:

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

Of course, as a result, I got an error and "value =" div " . Expected result: 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 regex? I would like to do this in one regex.

Thanks.

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

Although you expected it to replace $1 , perl sees it as a $1123 variable. Perl doesn't know what you meant $1 . Therefore, you need to limit the variability 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 a script with the above modules results in an error message:

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

(ignore the reported script names and line numbers.) It clearly states what perl expected.

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

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

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" 
+1
source

Source: https://habr.com/ru/post/921855/


All Articles