my $count; while () { s/(this)/$count++;$1/ge; # non-destructive version } print "number of this = $count\n";