#!/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