Hi. I'm trying to write a conditional based on the number of occurrences of $sub in a constant string.

I couldn't find a concise solution on perldoc, though there was an alternative where a loop was used. This says m// is meant to return the number of matches. It doesn't seem to do that. The test code below is what they have in their s/// example, except with m instead of s.

my $str = "thisthis"; if ( my $n = ($str =~ m/this/g) ) { print qq{Found $n occurrence(s) of "this"\n}; }

This outputs "Found 1 blah".

Some context (pun not intended) might help. Essentially, I want to code "If $sub occurs more than N times in '<string>', then do something". I can think of a lot of bad ways to do this, but not a good way to do it.

In the following extract, we're trying to print "Yes" if "0.0.0.0" occurs more than N times in the output of some command. There's a useless array there to gather the results in a list, the length of which being what I want to base a decision on.

print "Yes" if( (my @a = `route print`=~ m!0.0.0.0!g) > 3);

Is there a nice (ie, without my useless @a) way to return the number of matches from the regex search?

Thanks for your time

Update: Thanks all. Good answers all round. Helpful and concise (how perl should be :D). I'm not sure what the thanking protocol is here...didn't want to create a new reply D:


In reply to Count number of occurrences of a substr by Jerbear217

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.