open my $OUT, '>', 'output.txt' or die "output: $!"; for my $file (glob 'dir/*.txt') { # Your old code here. Remove opening the output file. }