my $filename = 'counts.txt'; open (my $fh, '>', $filename) or die "Could not open '$filename' $!"; my $count = ""; while (my $line = <>){ if ($line =~ /^>hsa/){ $line = <>; $count .= length$line; $count .= " "; } } print $fh $count; close $fh;