use strict; my $number_of_files = 0; while () { chomp; my @line = split; # On the first list, set up the process if ($. == 1) { for (my $i = 1; $i < @line; $i++) { my $fh = "OUTPUT" . $i; my $filename = $line[$i] . ".txt"; open ($fh, ">$filename") or die "Cannot open the output file: $!"; } $number_of_files = @line; } else { for (my $i = 1; $i < @line; $i++) { my $fh = "OUTPUT" . $i; print $fh ("$line[0]\t$line[$i]\n"); } } } for (my $i = 1; $i <= $number_of_files; $i++) { my $fh = "OUTPUT" . $i; close $fh or die "Cannot close the output file: $!"; }