my $count = 0; $string =~ s/a(??{++ $count <= $N ? "(*ACCEPT)" : "(*FAIL)"})/i/g; # Use '""' instead of '(*ACCEPT)' and '(?!)' instead of '(*FAIL)' on old Perls.