On Tue, Aug 09, 2005 at 09:07:16PM -0700, Stephen A. Jarjoura wrote:
> Hey, all;
>  
> I needed to count the number of occurances of a substring within a string
> and used the following method, which worked. I am just wondering if there
> is a better way to do it, or (god forbid) a "best practice".
> 
> ## $buffer contains an entire XML file
> $buffer =~ s/(\<transfer)/$transfer_count++;$1/sg;
> print "Transfer Count: $transfer_count\n";
>  
> Did I miss some obvious, and easier method?
>  

Basically, you need a loop.  s///g allows you to hide the loop, but is less
efficient because you're updating the string.  You could use m//g with an
explicit loop instead:

$transfer_count++ while $buffer =~ m/\<transfer/g;

Ronald
 
_______________________________________________
Boston-pm mailing list
[email protected]
http://mail.pm.org/mailman/listinfo/boston-pm

Reply via email to