Replace string in perl script

I have a code:

my $orgstr = "\$map_remain{3}{1}=\"\${prefix}_123456\";";
my $cell   = "\${prefix}_123456";
$orgstr =~ s/$cell/abc/;
print "new str: $orgstr\n";

i want to replace ${prefix}_123456 to abc but this

$orgstr =~ s/$cell/abc/;

does not do , i dont know why, pleae anyone can help this ?

>Solution :

In Perl, the dollar sign $ and the curly braces {} are special characters used to denote variables and variable interpolation. In order to use them in a regular expression substitution, you need to escape them using a backslash .

Try modifying your code as follows:

my $orgstr = "\$map_remain{3}{1}=\"\${prefix}_123456\";";
my $cell   = "\${prefix}_123456";
$orgstr =~ s/\Q$cell\E/abc/;
print "new str: $orgstr\n";

The \Q and \E are used to escape all the special characters between them. In this case, it will escape the $ and the {} in $cell. This should allow the substitution to work as expected.

I used ChatGPT for help. Maybe it can help you.
Chúc may mắn

Leave a Reply