http://www.perlmonks.org?node_id=995641


in reply to Re: Limiting number of regex matches
in thread Limiting number of regex matches

I do like Dave's answer. But there is one thing that he didn't tell us which is that $count has to be initialized before calling this statement when using strict and warnings. $limit could have been a constant and I think that is the same.
#!/usr/bin/perl -w use strict; my $str='dog dog horse dog cow dog pig dog'; my $count =0; # won't work unless $count intitialized to 0 # simple declaration of "my $count; or a "my" # variable within in this type of complex perl # statement doesn't work under strict and warnings. # Or at least I've not been able get this # kind of stuff to work before. # But given my caveats, this does work! # whether is is better or not is left to # the readers.. my $limit =3; $count++ while $count < $limit && $str =~ m/dog/g; print "$count dogs were counted\n"; my $str2 = "horse dog cow"; $count = 0; #needed for initialization $count++ while $count < $limit && $str2 =~ m/dog/g; print "$count dogs were counted\n"; __END__ 3 dogs were counted 1 dogs were counted
Now one good thing about Dave's code is that it will stop after a certain number of matches - or at least I think that is what is going to happen (the match global gizmo can be modulated and monitored as it progresses). Whether or not that really matters depends upon the length of the string and the number of "dogs". I would claim that with less than 20 animals, it doesn't matter at all. Once the string gets much bigger than than that, well, it could matter. Software is art with science as a base, but there are exceptions to every "rule". What is the best in this application is just not known. That's why I show some examples of how to use Dave's code. Its a good idea and worthy of consideration, especially if the data set is very large.