use warnings; use strict; my @fh; # Store filehandles open $fh[@fh], '<', $_ or die "Can't open `$_': $!" for <1039418/*.txt>; while (1) { no warnings qw/uninitialized io/; my $line; $line .= <$_> // "\n" for @fh; last if $line =~ /^\n*$/; # All files finished or blank $line =~ s/\n(?!\z)/,/g; # Delimit with commas, except for last \n print $line; }