|
|
| No such thing as a small change | |
| PerlMonks |
Swap foo and bar in text?by Cody Fendant (Monk) |
| on Apr 18, 2012 at 04:36 UTC ( #965610=perlquestion: print w/ replies, xml ) | Need Help?? |
|
Cody Fendant has asked for the
wisdom of the Perl Monks concerning the following question:
Say I wanted to do this: $str =~ s/foo/bar/g; $str =~ s/bar/foo/g; I would obviously have a problem, because a "foo" in the original would be changed back to a "foo". by the second replacement. The way I do it manually in a text/WP app is: $str =~ s/foo/%%%/g; # or any other extremely unlikely string $str =~ s/bar/foo/g; $str =~ s/%%%/bar/g; but is there a better way to do it? $str =~ s/(foo|bar)/$1 eq 'foo'?'bar':'foo';/ge; works, and benchmarks better than the other way (string with 1,000 chars). Anything else monks can suggest?
Back to
Seekers of Perl Wisdom
|
|
||||||||||||||||||||||||||||||||