how to tr this?

2009-12-07 Thread 小兰
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?

Thanks.

//Xiao lan

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




Re: how to tr this?

2009-12-07 Thread Shlomi Fish
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/




Re: how to tr this?

2009-12-07 Thread John W. Krahn

Xiao Lan (小兰) wrote:

Hello,


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?


$ perl -e'
my @data = qw/
aaaa
bbbbaa
aaxxxbb
bb776yhghhaa
/;
for ( @data ) {
print $_ to ;
s/(aa|bb)/ ( my $x = $1 ) =~ tr|ab|ba|; $x /ge;
print $_\n;
}
'
aaaa to bbbb
bbbbaa to aaaabb
aaxxxbb to bbxxxaa
bb776yhghhaa to aa776yhghhbb




John
--
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity.   -- Damian Conway

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/