Perl: Count occurrences of substring  

I needed a quick way to count the number of times a substring appears in a larger string.

$count = @{[$haystack =~ /$needle/g]};

Updated: This is a more clear solution:

my $count = scalar(split(/$needle/,$haystack)) - 1;

Lots of good options found in the comments though.

Leave A Reply - 1 Reply
Replies
Mike Mitchell 2010-10-01 08:09am - No Email - Logged IP: 149.173.11.151
That's the slowest way.
See http://www.chengfu.net/2005/10/count-occurrences-perl/
All content licensed under the Creative Commons License