Hi Xiaolan!
On Monday 07 Dec 2009 12:20:45 Xiao Lan (小兰) wrote:
Hello,
I have a text whose content is like:
aaaa
bbbbaa
aaxxxbb
bb776yhghhaa
I want to switch all aa and bb.
I can handle this use regex:
s/aa|bb/$ eq 'aa'?'bb':'aa'/ge;
But how to use 'tr' doing that?
The short answer is that you cannot. The tr/// operator operates only on
characters. so tr/ab/ba/ will also change ac to bc and ab to ba, etc.
I once contemplated writing something called strtr to convert entire strings
into different ones, but then thought it would be too much trouble for too
little gain and that s/// can do all that and more.
Your s/// solution is OK, though you should:
1. Avoid using $ because it makes things slower globally. See the warning on
perldoc perlvar:
http://perldoc.perl.org/perlvar.html
Instead, do:
s/(aa|bb)/$1 eq 'aa' ? 'bb' : 'aa'/ge;
2. You may opt to use a hash for more complicated substitutions.
Regards,
Shlomi Fish
Thanks.
//Xiao lan
--
-
Shlomi Fish http://www.shlomifish.org/
Humanity - Parody of Modern Life - http://shlom.in/humanity
Bzr is slower than Subversion in combination with Sourceforge.
( By: http://dazjorz.com/ )
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/