Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Answer: How do I replace a substring (if exists) with a different substring in a string?

by tachyon (Chancellor)
on Jul 20, 2001 at 15:43 UTC ( #98373=categorized answer: print w/replies, xml ) Need Help??

Q&A > strings > How do I replace a substring (if exists) with a different substring in a string? - Answer contributed by tachyon

You can use a s/// regex like this:

my $str = "I have a dream"; my $find = "have"; my $replace = "had"; $find = quotemeta $find; # escape regex metachars if present $str =~ s/$find/$replace/g; print $str;

The quotemeta lets you find strings that contain regex meta characters and the /g at the end of the s/// does all occurances.

cheers

tachyon

  • Comment on Answer: How do I replace a substring (if exists) with a different substring in a string?
  • Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2017-12-12 12:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What programming language do you hate the most?




















    Results (332 votes). Check out past polls.

    Notices?