Reputation: 29096
How to simply do a search/replace in Perl? The following example doesn't work:
#!/usr/bin/env perl
use strict;
use warnings;
my $text = '***/**/*abc*/***//*';
my $search = '/*abc*/';
my $replace = '#def#';
print "$text\n";
$text =~ s/$search/$replace/g;
print "$text\n";
Upvotes: 0
Views: 46
Reputation: 50647
Make sure that content of $search
has quoted meta-chars by using \Q
or quotemeta
in order to be treated as literal string,
$text =~ s/\Q$search/$replace/g;
Upvotes: 2
Reputation: 13664
$search
is not treated as a string, but as a regular expression. The character *
has a special meaning in regular expressions so you need to quote it. Try:
$search = quotemeta '/*abc*/';
Upvotes: 4