Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

counting matches in string w/o s/// ?

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi, everyone<br>I want to count the number of occurrences my pattern matches in a given string without using s///.&nbsp;&nbsp;I don't need to substitute or translate.&nbsp;&nbsp;I just need to count the matches.<br><br>For example:<br><br>$someStr = &quot;hihihi&quot;;<br>$someStr =~ /hi/;&nbsp;&nbsp;# evaluates to true not 3<br>$someStr =~ s/hi/hi/g;&nbsp;&nbsp;# evaluates to 3 but unnecessary substitution and s/// operator will not work with read only values<br><br>any suggestions how to do this efficiently with read only values, too?<br><br>Thanks,<br>Keith
 
Yeah, but you still use s/// ...<br>in fact, you could just do<br><br>$someStr = &quot;hihihi&quot;;<br>$count = ($someStr =~ s/hi/hi/g);<br><br>or <br><br>$someStr = &quot;hihihi&quot;;<br>$count = ($someStr =~ s/(hi)/$1/g);<br><br>but both still use s///;<br><br>I don't think there's an easier way, not that the ones above are hard.&nbsp;&nbsp;If only m// returned the number of matches instead of true or false, that would be much more useful (esp. since 0 evals to false and any other number to true)<br>&nbsp;<br>
 
Well, it at least keeps the original variable as read-only.&nbsp;&nbsp;The string is left intact while you also compute the integer.&nbsp;&nbsp;What else do you need?&nbsp;&nbsp;I don't think there is another way to do it.<br> <p> Sincerely,<br><a href=mailto: > </a><br><a href= Anderson</a><br>CEO, Order amid Chaos, Inc.<br>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top