open in, "rep_set_ass_tax.fna"; while ($line=) { if($line=~/>/) { @vettore=split(/\s+/, $line); open my $fh, ">>seq_id.txt" or die "Cannot open output.txt: $!"; # There is no need to open a file each time you need to print something into it if it is the same file. just open it once before the loop and print to it foreach (@vettore); # What is a loop and what is a proper way to write one. So you started a loop and what are you going to do with it(I mean variables in the loop) print $_ . "\n"; # OK, so you want to print something, but where to STDOUT or into a file that you have opened close my $fh; # again my doesn't have any effect if use strict is not called. } }