SPUG: To sum it up... counting the number of occurences...

Matt Tucker tuck at whistlingfish.net
Mon Dec 18 18:30:14 CST 2000


-- Jonathan Gardner <gardner at sounddomain.com> spake thusly:

> There is a similar one:
>
> $count = 0;
> $count ++ while ($string =~ /a/g); # Thanks to Joel Grow
>
> That matches em all, puts it in an array and iterates over the array
> incrementing count each time. I learn more about "while" and
> "for/foreach" every day in perl. Those two functions have endless
> possibilities...

Actually, this doesn't store the matches in an array. It executes the match and iteration until it doesn't get any more matches. An important 
distinction if you're worried about speed and space issues.

To do what you're talking about, you would do:

$count++ foreach $string =~ /a/g;
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 232 bytes
Desc: not available
Url : http://mail.pm.org/archives/spug-list/attachments/20001218/422e91a5/attachment.bin


More information about the spug-list mailing list