http://qs1969.pair.com?node_id=292858


in reply to a Couple of questions!

$count = $data =~ m/and/; i have tried a way for the matching operator to count the occurences

I don't think the ordinary match operator (m//) does that. I think it just returns true (it matched) or false (no match) in scalar context. In list context, though, it will return a list consisting of the last item matched by each set of parens, which still isn't what you want, since you want to know how many times a given set of parens matched. However, if you have no parens, then I think it returns a list of all the matches of the whole string. If you assign that to an array, *then* evaluate it in scalar context, you should be able to get a count.

my @matches = $data =~ m/and/; my $count = scalar @matches;

Or, more tersely...

my $count = @{[$data=~m/and/]}
i also tried it with the global modifier /g

You could do that in a loop (see below). Note that s///g and m//g do slightly different things.

For counting individual characters, it is generally considered that tr/// is the fastest way, but of course that won't work for something several chars long. There are, of course, other ways to accomplish what you want...

You can get a good approximation with split...

my $count = (scalar split /and/, $data) -1;

One problem with this approach is that it uses extra memory temporarily; if your string is really really long, that could be an issue. (For a string of any sane length, though, it won't matter.) Also, it causes copying of most of the content of the string (again, temporarily), so if this is going to happen many many times in a nested loop it could perform badly. Perhaps the worst problem is that if your pattern (in the example, /and/) matches at the beginning or end of the string that will throw your count off by one.

There are other ways to do it. For example, you could go back to using m//g in scalar context after all; it returns true once for each match, and you can count by incrementing a pointer.

my $count=0; while ($data=~m/and/g) { ++$count }

$;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/