in reply to varaible to filehandle -alack!

You might be better off to use a lexical hash to hold your filehandles rather than $1. You also ought to cater for the possibility of lines that don't match your pattern. I have changed your pattern, substituting a negated character class ([^\t]+) for your non-greedy .*? as that is perhaps safer.

In the code below I use a HEREDOC as my input and references to scalars (actually hash values) as my output just to avoid creating loads of files on my disk; the principle will work just as well with real files.

use strict; use warnings; open my $alusFH, q{<}, \ <<EOD or die qq{open: << HEREDOC: $!\n}; chrabc123 blah blah chrdef456 burble blurgh Duff line to be rejected chrabc123 rootle tootle EOD my %seen; my %fileHandles; my %outputFiles; while ( <$alusFH> ) { if ( m{^(chr[^\t]+)\t} ) { do { open $fileHandles{ $1 }, q{>}, \ $outputFiles{ $1 } or die qq{open: > scalar ref.: \n}; } unless $seen{ $1 } ++; print { $fileHandles{ $1 } } $_; } else { warn qq{Bad line: $_}; } } close $alusFH or die qq{close: << HEREDOC: $!\n}; do { close $fileHandles{ $_ } or die qq{close: > scalar ref.: \n}; } for keys %fileHandles; print qq{$_:\n\n$outputFiles{ $_ }----------\n} for sort keys %outputFiles;

Here's the output.

Bad line: Duff line to be rejected chrabc123: chrabc123 blah blah chrabc123 rootle tootle ---------- chrdef456: chrdef456 burble blurgh ----------

I hope this is of interest.

Cheers,

JohnGG