Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-04-26 00:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found