mkHun mkHun - 3 months ago 12
Perl Question

How to open the multiple files dynamically using a dynamic file handle

I'm trying to opening multiple files using the a dynamic file handle but it doesn't work.

for my $i ( 1 .. $#genome_list ) {
my $fh = "RESULT$i";
open my $fh, "<", "filename$i"; # here is the problem
}


Then how to access the data of the given handler.

When I run the program it shows this error

Can't use string ("RESULT1") as a symbol ref while "strict refs"


How can I fix it?

Answer

You're trying to do something that's a little bit nasty, and rather than tell you how to do that, I'm going to suggest an alternative.

If you need multiple filehandles open at once, then what you need is a hash:

my %file_handle_for;
for my $i ( 1..$#genome_list ) { 
    open ( $file_handle_for{$i}, '<', "filename$i" ) or die $!;
}

Then you can just access the file as:

print {$file_handle_for{$i}} "Some text\n"; 

Or:

while ( <{$file_handle_for{$i}}> ) {
    print;
 }

etc.

That's assuming of course, you need to open all your files concurrently, which you may well not need to.

The above is the general solution to wanting to use variables as variable names.

Looking at it in your case though - you're opening files in numeric order with no gaps, and that means an array is better suited.

my @filehandle_for; 
#note though - arrays start at zero normally, so you might be missing one here!
foreach my $number ( 1..$#genome_list ) { 
  open ( $filehandle_for[$number], '<', "filename$number" ) or die $!;
}