in reply to Re: Counting SubStrings, Style Question
in thread Counting SubStrings, Style Question

Although the OPed question does not seem to be concerned with overlapping occurrences, they can also be handled with m{pattern}g. If the sub-string may contain regex metacharacters, it is also wise to meta-quote.

>perl -wMstrict -le "my $substring = 'xxx'; for my $string (@ARGV) { my $non_overlap =()= $string =~ m{ \Q$substring\E }xmsg; my $overlap =()= $string =~ m{ (?= (\Q$substring\E)) }xmsg; print qq{$non_overlap non-overlapping $substring in $string}; print qq{$overlap overlapping $substring in $string}; } " x xx xxx xxxx xxxxx xxxxxx 0 non-overlapping xxx in x 0 overlapping xxx in x 0 non-overlapping xxx in xx 0 overlapping xxx in xx 1 non-overlapping xxx in xxx 1 overlapping xxx in xxx 1 non-overlapping xxx in xxxx 2 overlapping xxx in xxxx 1 non-overlapping xxx in xxxxx 3 overlapping xxx in xxxxx 2 non-overlapping xxx in xxxxxx 4 overlapping xxx in xxxxxx

Update: The capturing group in  m{ (?= (\Q$substring\E)) }xmsg is needed only if there is a concern with what matched rather than only with how many matched as in the OPed question.

Replies are listed 'Best First'.
Re^3: Counting SubStrings, Style Question
by LanX (Saint) on Mar 20, 2010 at 21:14 UTC
    > If the sub-string may contain regex metacharacters, it is also wise to meta-quote.

    the same when using split.

    Cheers Rolf