Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading