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 - 2 Replies
Replies
Mike Mitchell 2010-10-01 08:09am - No Email - Logged IP: 149.173.11.151
mateusz 2012-11-19 08:03am - No Email - Logged IP: 131.130.60.244

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