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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pattern matching - newbie

Status
Not open for further replies.

snookmz

Programmer
Apr 17, 2001
46
AU
G'day all

Iv been searching through the pattern matching information in my perl books, and i just cannot get my head around how to get the number of occurances of a particular string in a buffer...

i.e. I want to search a buffer for a particular string, to find out how many times it occurs within that buffer... Any ideas????

thanks in advance /-------------------------------------
| I always have been, and always will |
| be, a newbie :) |
\-------------------------------------
 
Just use a while loop that increments your count on each iteration. e.g.

Code:
$count = 0;
while($variable =~ /pattern/g) { $count++; }

Hope this helps,

brendanc@icehouse.net
 
It's actually even easier than that. In a list context a pattern match will return the list of all parenthesized expressions. If there are no parentheses the entire expression is treated as if it were in parentheses. So just assign the results of the match to a list and take the number of elements in the list.
Code:
@matches = ($variable =~ /pattern/g);
$count = scalar(@matches);
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top