# First declare your file handle my $OUT; ... foreach ... { while ... { if ... { # Error found, so... # open the file if not open yet if (!defined $OUT) { open $OUT, '>', "$path/$file" or die "Uggabug! $!"; } # and log the error print $OUT "Yer error message\n"; } } } # finally, close it if you've opened it close($OUT) if defined $OUT;