nowox
nowox

Reputation: 29096

Trivial search/replacement in Perl without error?

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

Answers (2)

mpapec
mpapec

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

tobyink
tobyink

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

Related Questions