foreach my $file2 (@file2only) { my $flag = undef; my @dir_struct = split('\',$file2); foreach my $item (@dir_struct) { $flag = 'skip' if ($item =~ /^(temp|recycle|history)$/); last if ($flag eq 'skip'); } print OUT $file2 unless ($flag eq 'skip'); }