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


In reply to Re: varaible to filehandle -alack! by johngg
in thread varaible to filehandle -alack! by maayanster

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.