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.
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:
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Count number of occurrences of a substr
by toolic (Bishop) on Sep 28, 2011 at 18:47 UTC | |
Re: Count number of occurrences of a substr
by ikegami (Patriarch) on Sep 28, 2011 at 18:45 UTC | |
Re: Count number of occurrences of a substr
by aaron_baugher (Curate) on Sep 28, 2011 at 19:10 UTC | |
by FunkyMonk (Chancellor) on Sep 30, 2011 at 22:18 UTC | |
Re: Count number of occurrences of a substr
by hbm (Hermit) on Sep 28, 2011 at 18:45 UTC | |
by ikegami (Patriarch) on Sep 28, 2011 at 18:53 UTC | |
Re: Count number of occurrences of a substr
by Anonymous Monk on Sep 29, 2011 at 14:39 UTC |