Feed on

count matches in perl

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.

Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

3 Responses to “count matches in perl”

  1. on 10 Jul 2008 at 3:02 pm Michelle

    hey stinky! I googled “perl count matches” and you’re the top hit :-) btw, $match_count=()=$_=~m/a/g should also work.

  2. on 04 Nov 2009 at 10:19 pm urmom

    tr/a/a/ succeeds for individual characters but fails for longer strings

  3. on 23 Jan 2010 at 8:21 am Alex

    $counter++ while $_ =~ /a/g;

    Works like charm.

Did I get this wrong? Let me know!

Trackback URI | Comments RSS