0

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?

mkHun
  • 5,891
  • 8
  • 38
  • 85
  • Possible duplicate of [How can I use a variable as a variable name in Perl?](http://stackoverflow.com/questions/1549685/how-can-i-use-a-variable-as-a-variable-name-in-perl) – Chankey Pathak Aug 24 '16 at 10:48
  • Is that definitely `1..$#genome_list` - because `@genome_list` probably starts at `0`... – Sobrique Aug 24 '16 at 11:02

1 Answers1

4

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 $!;
}
Sobrique
  • 52,974
  • 7
  • 60
  • 101
  • 3
    Wouldn't this be better as an array, since the keys are a contiguous range of integers? – Borodin Aug 24 '16 at 10:45
  • Probably, yes. I was thinking in terms of it being a 'string' they're trying to use as a key, despite it being numbered. – Sobrique Aug 24 '16 at 10:51