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?percentage_way: 130 wallclock secs (126.01 usr + 0.29 sys = 126.30 CP +U) @ 7917.66/s (n=1000000) rhs_way: 49 wallclock secs (46.50 usr + 0.13 sys = 46.63 CPU) @ 21 +445.42/s (n=1000000)
Back to
Seekers of Perl Wisdom