Struggle with "simple" replacement

A

Arne

Trying to make a simple replacement of strings I spent some hours
resulting in this:

#!/usr/bin/perl -w
#use strict;

$_ = "Just {Test4*4}";
#my $old = "{Test4*4}"; #(i) normal double quoted match
my $old = "\{Test4\*4\}"; #(ii) escaping meta chars
#my $old = '{Test4*4}'; #(iii) using single quotes
my $new = "okay";
s/$old/$new/;
print "$_\n";

It should just demonstrate how to substitute a substring containing
meta chars (e.g. { or *). I had expected that avoiding interpolation
by escaping would help. But even single quote strings aren't better.
Tell me why I am such a fool. would appreciate.

Arne
 
S

Sam Holden

Trying to make a simple replacement of strings I spent some hours
resulting in this:

#!/usr/bin/perl -w
#use strict;

$_ = "Just {Test4*4}";
#my $old = "{Test4*4}"; #(i) normal double quoted match
my $old = "\{Test4\*4\}"; #(ii) escaping meta chars

That doesn't escape anything. { and * are not "special" in
a double quoted string so the backslashes are essentially ignored
(or \{ is converted to { and so on).
#my $old = '{Test4*4}'; #(iii) using single quotes
my $new = "okay";
s/$old/$new/;
print "$_\n";

It should just demonstrate how to substitute a substring containing
meta chars (e.g. { or *). I had expected that avoiding interpolation
by escaping would help. But even single quote strings aren't better.
Tell me why I am such a fool. would appreciate.

perldoc -f quotemeta

or to do things the hard way:

"\\{Test4\\*4\\}"

or

'\{Test4\*4\}'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top