more useful options | |
PerlMonks |
Count number of occurrences of a substrby Jerbear217 (Initiate) |
on Sep 28, 2011 at 18:27 UTC ( [id://928383]=perlquestion: print w/replies, xml ) | Need Help?? |
Jerbear217 has asked for the wisdom of the Perl Monks concerning the following question: 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.
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:
Back to
Seekers of Perl Wisdom
|
|