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. } } #### use strict; use warnings; open(IN, "<", "rep_set_ass_tax.fna") or die "Died!!"; open (OUT , ">","seq_id.txt") or die "Cannot open output.txt: $!"; while (my $line=) { if($line=~/>/) { my @vettore=split(" ", $line); foreach (@vettore){ print OUT $_ . "\n"; } } } close IN; close OUT; #### use strict; use warnings; open(IN, "<", "rep_set_ass_tax.fna") or die "Died!!"; while (my $line=) { if($line=~/>(\d+)/) { print $1 . "\n"; } } close IN; #### >1 ATGT... >2 ATGGTGC.. #### use strict; use warnings; my $infile = "rep_set_ass_tax.fna"; my $outfile = "seq_id.txt"; # you need to open this only if writing to a file open(IN, "<", $infile) or die "Died!!"; while (my $line=) { if($line=~/>\s*(\d+)/) { print $1 . "\n"; } } close IN;