my $count = 0; while ($text =~ m{(a)}g) { substr($text, $-[0], $+[0]-$-[0], "XX"); last if ++$count >= 3; }