user5079076
user5079076

Reputation:

Perl: Replace string with/without "+" sign

I am trying to replace parts of string. Currently I am using a simple method as follows:

my $text = $ARGV[0];
my $in_d = $ARGV[1]; 
my $out_d = "Sample_text";

$text =~ s/$in_d/$out_d/;

The above code does not seem to work if there is a '+' sign involved. For e.g. for the code:

my $text = "I+here starving here";
my $input_d = "I\+here";
my $out_d = "I";
$text =~ s/$input_d/$out_d/;
print $text."\n";

Output:

I+here starving here

How do I make sure that the text gets replaced regardless of characters involved? Thanks for your help in advance.

Upvotes: 1

Views: 60

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174796

Use \Q, \E sequence to escape block of characters.

\Qfoo+\E

So, it would be

$text =~ s/\Q$input_d\E/$out_d/;

DEMO

Upvotes: 1

Related Questions