12/15 How would I count the number of occurances of a pattern in Perl?
\_ the easy but incorrect way to do it is grep pattern file | wc -l
\_ In a single line? In a file? In what?
\_ Find pattern. $count++;
\_ Yeah, this would work if I'm feeding a for loop line by
line. But what if you have say $foo = "aaabbbaaacccaaa"
and you want to count the number of times 'aaa' appears?
\_ Use the same algorithm. Implement "find pattern" differently.
Twink. Try while ($foo =~ m/pat/g) { $count++ } or
$count = length($foo =~ m/pat/g);
\_ Thanx, but can anyone ask anything on this motd without
being branded a twink? I guarantee you there is not
one question here that someone won't think is trivial
or self-evident or just plain dumb.
\_ you then have to decide if "aaaaaa" matches with "aaa"
once, twice, or 5 times.
\_ troll deleted -tom
\_ tr/// it into its identical string/pattern and catch the returned
result in a variable. The result will be the number of times
the translation (in this case the null translation) was
performed. Example from camel book:
$cnt = $sky =~ tr/*/*/; # count the stars in $sky
-brain |