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.


In reply to Re^2: Counting SubStrings, Style Question by AnomalousMonk
in thread Counting SubStrings, Style Question by se@n

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.