count matches in perl
January 4th, 2007 by Lawrence David
say you’d like to count the number of times you match a string in perl. there’s a quick and easy way to do it using the ‘tr’ function. for instance, to count the number of ‘a’s in a string:
$_ = “asdfasdfaf”;
$match_count = tr/a/a/;
note that what you’re actually doing is counting the number of times a is being substituted with itself.
hey stinky! I googled “perl count matches” and you’re the top hit btw, $match_count=()=$_=~m/a/g should also work.
tr/a/a/ succeeds for individual characters but fails for longer strings
$counter++ while $_ =~ /a/g;
Works like charm.