in reply to tr/abc// won't use string

Editor's Note - Masem - 2001-07-19 - Please note text of original question was given below with an empty root node; this text has been copied into the root node for completeness' sake.

I understand that tr/abc// use "abc" for matching, instead it uses "a", "b", and "c" to match $_ separately.
Therefore this counting won't work correctly:

$x = 0; $cnt = tr/abc//; $x += $cnt;
I've tried:
$x = 0; while (<DATA>) { $cnt = m/abc/g; $x += $cnt; }
This won't work either... So, is there a way to find out how many times string "abc" appeared?

Could any Perl Master enlighten me a little bit?

Replies are listed 'Best First'.
Re: Re: tr/abc// won't use string for matching, then what?
by jynx (Priest) on Jul 19, 2001 at 22:33 UTC

    First,

    Here's a quick hack that will work:

    my $cnt = 0; while (<DATA>) { $cnt++ while m/abc/g; } print "number of entries: $cnt\n";
    Second,

    While i'm not entirely certain on this (hopefully another monk will straighten this out if i'm wrong), the snippet you tried doesn't work because m// returns whether it matched or not, not the number of times it matches. So if there are lines that have multiple matches, you won't get the total number of matches on that line.

    Hope This Helps,
    jynx

    Update:rewrote my snippet to be more idiomatic...

Re: Re: tr/abc// won't use string for matching, then what?
by supernewbie (Beadle) on Jul 19, 2001 at 22:36 UTC
    I now tried:
    $x = 0; while (<DATA>) { ++$x while($_ =~ /abc/g); }
    but it is still not counting "abc" right....
    What did I do wrong?

      at this point,

      i should have asked previously, excuse me for the delay, but it might help to know what results you're actually getting and what version of perl you're using. This may help for further debugging...

      jynx