Forum Moderators: coopster & phranque

Message Too Old, No Replies

This is a silly question.

         

ktsirig

11:23 am on Jan 31, 2006 (gmt 0)

10+ Year Member



Hi all!
My question is rather silly, but I can't seem to be able to find the solution myself...

I have the array:
@letters = (A,B,C,D,E,F);

and the string:
$string = "AFTYUBEWTWECRTUTYIYTDDDDRYJURTHJTREEEEEFGSDFF";

and I want to find how many times each letter appears in the $string.

I go like:

foreach $a(@letters)
{
$count = ($string = ~tr/$a//);
print $count;
}

But it doesn't count anything...
Does it have to do with the $a in the pattern matching?
I tested the same thing and instead of $a I put A or B etc and it works...

perl_diver

6:35 pm on Jan 31, 2006 (gmt 0)

10+ Year Member



The tr/// operator does not support variable interpolation. Which is why A works and $a doesn't. Switch to s/// instead of tr/// and it should work, like so:


foreach $a (@letters)
{
$count = ($string =~ s/$a/$a/g);
print "count of $a = $count\n";
}

or you can use the map function too:


foreach $a(@letters)
{
$count = map{m/$a/g} $string;
print "count of $a = $count\n";
}

ktsirig

7:27 am on Feb 1, 2006 (gmt 0)

10+ Year Member



Thanx perl_diver,
nice to see you replying in one of my topics so soon
:)))

Problem solved