opendir (DIR, "$responseDir") or die "could not open $responseDir :$!\n"; foreach $file ( readdir(DIR) ) { open THISFILE, "$responseDir/$file"; my @newFile = grep { /$commonField/ } ; if ( @newFile ) { # If there were any contents, this is our file. $matchedfile = $file; close THISFILE; last; } close THISFILE; } closedir(DIR); print "Matched file $matchedfile.\n";