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.

Tags:
Leave A Reply - 2 Replies
Replies
October 1st 2010 - Mike Mitchell
November 19th 2012 - mateusz

heres a better way: $count = () = ($haystack =~ /$needle/g);

g - all occurrences =~ - find occurrences

() - count number of elements

how the f can you name a function () or =~? imagine googling perl () examples. in php it is substr_count, in python .count() and in perl? ()=++$p[[]][/%@//f/f/. if perl was low level programming language i could understand. but its not.

All content licensed under the Creative Commons License