11/4 Ok, I rtfm'd and stfw'd. How in perl do I swap 'foo' with 'bar' and
'bar' with 'foo'? I assume it has to be one s///g statement, but how?
\_ let the "I can do this in .... notes" olympics begin!
I'll start. I think you want:
perl -pi -e `s/foo/bar` filename
\_ I wonder if perl is a good candidate for upperbounding kolmogorov
complexity of various text processing programs.
\_ I think he wants to swap them. Not just simple replace. There's
probably a more elegant way, but easiest is to use three replaces:
s/foo/%%placeholder%%/g
s/bar/foo/g
s/%%placeholder%%/bar/g
If it's a complex match, you'll probably want to do grouping,
and will need some temp variables to save grouping matches across
s/// statements, --scotsman
\_ Ah ok. Thx. I was thinking there was some magical perl
operator that would do this for me in one statement.
\_ s/foo|bar/{foo=>'bar',bar=>'foo'}->{$&}/ge
--dbushong
\_ niloc's shortened solution:
s/foo|bar/$& eq'foo'?'bar':'foo'/ge
-geordan
\_ Wow, look at all that wasted white space... :-)
\_ Neat. Thx again.
\_ slight tweak:
s/foo|bar/$> c?bar:foo/ge
-alexf
\_ Works only on the "foo/bar" case, but I
appreciate the sentiment. It also gives
bareword warnings, I think. -geordan
\_ Not in the raw perl -pe context on soda;
it'll (naturally) start screaming bloody
murder once it's using -w or something like
that. A hack's a hack =) -alexf |