while(my $job_B=readdir(DIR_B)){ print "D\n"; next unless $job_B =~ /Out_$tag\.txt$/; } #### next unless $job_B =~ /Out_$tag\.txt$/; #.... until you have checked the whole directory and then goto: beginning.