my %fh; # hash of filehandles while ( <> ) { # do something to find out the $subcat(egory) # and open the file if not done already $fh{$subcat} || open($fh{$subcat}, ">$pathtofile" or die "Aaargh: $!"; # now you can print stuff to the file print { $fh{$subcat} } @stuff; } # Close down everything close $_ foreach values %fh;