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)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Swap foo and bar in text?
by davido (Cardinal) on Apr 18, 2012 at 04:46 UTC | |
by Cody Fendant (Hermit) on Apr 19, 2012 at 03:52 UTC | |
|
Re: Swap foo and bar in text?
by GrandFather (Saint) on Apr 18, 2012 at 05:00 UTC | |
by Jim (Curate) on Apr 20, 2012 at 07:17 UTC | |
by GrandFather (Saint) on Apr 20, 2012 at 08:33 UTC | |
by Jim (Curate) on Apr 20, 2012 at 15:51 UTC |