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).
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.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);
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |