How do I perform multiple replacements with Perl?

user332951 picture user332951 · May 5, 2010 · Viewed 17.9k times · Source

I have Perl code:

my $s =  "The+quick+brown+fox+jumps+over+the+lazy+dog+that+is+my+dog";

I want to replace every + with space and dog with cat.

I have this regular expression:

$s =~ s/\+(.*)dog/ ${1}cat/g;

But, it only matches the first occurrence of + and last dog.

Answer

WhirlWind picture WhirlWind · May 5, 2010

Two regular expressions might make your life a lot easier:

$s =~ s/\+/ /g;
$s =~ s/dog/cat/g;

The following matches "+," followed by a bunch of stuff, followed by "dog." Also, "+" is technically a metacharacter.

/+(.*)dog/