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.
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$1by specifying it as${1}: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.
For example, running your script with the above modules included results in the error message:
(Disregard the reported script name and line numbers.) It clearly states what perl expected.
Another approach using look-behind and look-ahead assertions: