in reply to counting inside the loop

$count{$t1}++

This will have the number of occurences of each combination stored in a hash. Think about how it works and you will know where to put it. If not, try out a few locations and observe what happens. Don't forget to print out the hash after all the loops are finished.

my $count=($str2=~ tr/$t1//);

This will count how often the characters in $t1 are in $str2, i.e. if $t1 were "ab" it would count all 'a's and 'b's in $str2. Is that really what you want?

Replies are listed 'Best First'.
Re^2: counting inside the loop
by AnomalousMonk (Archbishop) on Jun 30, 2011 at 15:09 UTC
    my $count=($str2=~ tr/$t1//);

    This will count how often the characters in $t1 are in $str2 ...

    Unfortunately, the  tr/// operator does not interpolate, but the  s/// or, better yet, the  m// operator can serve here:

    >perl -wMstrict -le "my $s = 'foo bar fooo bar foooo bar'; my $cc = 'foz'; ;; my $count = ($s =~ tr/$cc//); print $count; ;; $count = '$c$c$' =~ tr/$cc//; print $count; ;; $count = $s =~ tr/foz//; print $count; ;; $count = $s =~ s{ ([$cc]) }{$1}xmsg; print $count; ;; $count =()= $s =~ m{ [$cc] }xmsg; print $count; ;; $count = $s =~ s{ [$cc] }{}xmsg; print $count; print qq{'$s'}; " 0 5 12 12 12 12 ' bar bar bar'

    Note: There is no need for a capture group in the  s/// expression if characters in the string can be counted 'destructively':
        $count = $s =~ s{ [$cc] }{}xmsg;

    Update: Added  s/// and  m// examples, discussion.

Re^2: counting inside the loop
by sarvan (Sexton) on Jul 01, 2011 at 11:09 UTC
    Hi, For this,
    $count=($str=~ tr/($t1)//);

    if $t1 has ab. i just want to count how many times ab is their in $str. together. not as seperately 'a' 'b'.

    What can be done for that..
        Hi,
        $s='finding related pages finding on the world wide web'; my $count=$s=~ m/finding/g; print $count;

        I expect the result as 2.. becus "finding" exists two times in $s. but the output is 1. Why??

        thanks