[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[MacPerl] Unexpected behavior from tr function



I am trying to use the tr function to count the frequency of letters 
in a string and I am running into some unexpected behavior.  Here's 
my code:

#!perl -w

my ($test, $a, $b, $c);

$test = "aaabbbaabbccccacab";
$a='a'; $b='b'; $c='c';

print "\nUsing literal values in tr ...\n";
print "Frequency of a in $test: " . $test=~tr/a/a/ . "\n";
print "Frequency of b in $test: " . $test=~tr/b/b/ . "\n";
print "Frequency of c in $test: " . $test=~tr/c/c/ . "\n";

print "\nUsing variables in tr ...\n";
print "Frequency of a in $test: " . $test=~tr/$a/$a/ . "\n";
print "Frequency of b in $test: " . $test=~tr/$b/$b/ . "\n";
print "Frequency of c in $test: " . $test=~tr/$c/$c/ . "\n";

print "\nTrying it in a loop ...\n";
foreach ('a','b','c') {
	print "Frequency of $_ in $test: " . $test=~tr/$_/$_/ . "\n";
}

__END__

Here's the output:

Using literal values in tr ...
Frequency of a in aaabbbaabbccccacab: 7
Frequency of b in aaabbbaabbccccacab: 6
Frequency of c in aaabbbaabbccccacab: 5

Using variables in tr ...
Frequency of a in aaabbbaabbccccacab: 7
Frequency of b in aaabbbaabbccccacab: 6
Frequency of c in aaabbbaabbccccacab: 5

Trying it in a loop ...
Frequency of a in aaabbbaabbccccacab: 0
Frequency of b in aaabbbaabbccccacab: 0
Frequency of c in aaabbbaabbccccacab: 0

Any ideas as to why $test=~tr/$_/$_/ doesn't work inside of a loop?

--rich

--
Richard L. Anderson
Network Manager
School of Community Service, University of North Texas
<mailto:anderson@unt.edu>

# ===== Want to unsubscribe from this list?
# ===== Send mail with body "unsubscribe" to macperl-request@macperl.org