简体   繁体   中英

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?

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 $!;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM