Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform multiple replacements with Perl?

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.

like image 988
user332951 Avatar asked May 05 '10 00:05

user332951


1 Answers

You can use the 'e' modifier to execute code in the second part of an s/// expression.

$s =~ s/(\+)|(dog)/$1 ? ' ' : 'cat'/eg;

If $1 is true, that means the \+ matched, so it substitutes a space; otherwise it substitutes "cat".

like image 159
Brock Avatar answered Sep 28 '22 00:09

Brock