A problem with tr

D

dn.perl

Code being run under ActiveState Perl (latest download) :
my $str1 = "11,11,2222,3" ;
$str1 =~ tr/,// ;
print "$str1 \n" ;

my $str2 = "11,11,2222,3" ;
$str2 =~ tr/,/Z/ ;
print "$str2 \n" ;
===

Output :
11,11,2222,3
11Z11Z2222Z3

So I am able to replace comma with 'Z' , but I am not able to make it
disappear using tr.
Why is that so?

Please advise. Thanks in advance.
 
M

Martien Verbruggen

On Wed, 10 Oct 2007 22:34:44 -0000,
my $str1 = "11,11,2222,3" ;
$str1 =~ tr/,// ;
print "$str1 \n" ;

my $str2 = "11,11,2222,3" ;
$str2 =~ tr/,/Z/ ;
print "$str2 \n" ;
===

Output :
11,11,2222,3
11Z11Z2222Z3

So I am able to replace comma with 'Z' , but I am not able to make it
disappear using tr.
Why is that so?

From the documentation of tr/// in the perlop document [1]:

Options:

c Complement the SEARCHLIST.
d Delete found but unreplaced characters.
s Squash duplicate replaced characters.

If the "/c" modifier is specified, the SEARCHLIST character set
is complemented. If the "/d" modifier is specified, any char-
acters specified by SEARCHLIST not found in REPLACEMENTLIST are
deleted.

But also, and this, I assume, is the source of your confusion:

If the "/d" modifier is used, the REPLACEMENTLIST is always
interpreted exactly as specified. Otherwise, if the REPLACE-
MENTLIST is shorter than the SEARCHLIST, the final character is
replicated till it is long enough. If the REPLACEMENTLIST is
empty, the SEARCHLIST is replicated. This latter is useful for
counting characters in a class or for squashing character
sequences in a class.

I suspect that what you're looking for is:

$str1 =~ tr/,//d;

Martien

[1] You can get to the documentation by using the man command on a
Unix-like OS, perldoc on almost any OS, and from HTML pages on some
distibutions. If you don't already know this, please take some time to
get familiar with Perl's documentation and your system's way of making
it available to you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,217
Latest member
topweb3twitterchannels

Latest Threads

Top