my @keepers; opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!"; while ($file = readdir()) { if ($file =~ /Somthing/ and -f $file and open(FILE, $file) { my $pass = 0; while () { $pass++ if (/\b(?:PASS|sweeps|Final)\b/); last if ( $pass == 3 ); } close FILE; push @keepers, $file if ( $pass == 3 ); } } # now do whatever needs to be done with @keepers.