my %handle = (); my $ref_db = FastaDb->new($fasta) or die("Unable to open Fasta file, $fasta\n"); while( my $seq = $ref_db->next_seq() ) { if($seq->header() =~ m/(K[0-9]{5})/){ my $ko = $1; if(!exists $handle{$ko}){ open my $fh, ">>".$outdir.$ko.".fasta"; $handle{$ko} = $fh; } print {$handle{$ko}} $seq->header()."\n".$seq->seq()."\n"; } } map { close $handle{$_} } keys %handle;