Using a hash (or possibly an array), as suggested by other monks above, for storing file handles is the easiest solution.

Just remember that, in order to print to a filehandle stored in a hash you need to put the handle within curly brackets. For example, if %fh is your hash of filehandles and if your chromosome id is 5, the your need to do this:

print {$fh{5}} "to be printed\n";

Another possible option to solve your problem is to use a dispatch table, i.e. to store in a hash anonymous functions printing to their own file handle (I have no environment on my mobile device to test this code right now).

my %dispatch: sub create_function { my $id = shift; open my $fh, ">", "file_nr_$id" or die "... $!"; return sub { my $line = shift; print $fh $line; } } $dispatch{$_} = create_functions($_) for @list_of_chromosomes; # ... # later when reading the file, assuming you have obtained a $line and +an id $id from the input: $dispatch{id}->($line);
The create_function subroutine is something that is sometimes called a function factory; it generates anonymous subroutines which close over their own filehandle. This anonymous subroutines are returned to the caller and stored in the %dispatch hash. Then, when reading the input, you just call the anonymous subroutine stored in the hash.

In reply to Re: Opening multiple output files within a loop by Laurent_R
in thread Opening multiple output files within a loop by TJCooper

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.