Couple of things :)
(1) You need to localize you global filehandle FILE. Otherwise all filehandles stored away in the array will refer to the most recently opened file...
local *FILE; open FILE, "<", "./$nbdc_dir/$file" or die ... ...
Or, even better, make use of the feature of more modern versions of Perl to accept a lexical variable in the open() statement:
open my $fh, "<", "./$nbdc_dir/$file" or die ... $nbdc_filehandles[$index] = $fh;
or even simply (if @nbdc_filehandles is lexical)
open $nbdc_filehandles[$index], "<", "./$nbdc_dir/$file" or die ...
The diamond operator is somewhat "special" syntactically, in that
(2) you need to make an explicit assignment if you use it outside of loops:
my $line = <$fh>;or
$_ = <$fh>;(3) no whitespace is allowed within the angular brackets:
$_ = <$fh>; # OK $_ = < $fh >; # not OK
(4) and, as jettero and BrowserUK pointed out, it doesn't accept array expressions, so you have to use an intermediate flat scalar, or readline():
my $fh = $nbdc_filehandles[$index]; $_ = <$fh>; # instead of # $_ = <$nbdc_filehandles[$index]>;
So, your code would look like
my @nbdc_filehandles; my @nbdc_data; my $index=0; foreach my $file (@nbdc_files) { open my $fh, "<", "./$nbdc_dir/$file" or die "Can't open ./$nbdc_d +ir/$file"; $nbdc_filehandles[$index] = $fh; #get the first set of data values $_ = <$fh>; $_ = <$fh>; chomp; #get rid of trailing \n $nbdc_data[$index] = [ split(/\t/, $_) ]; # ... $index++; } # then sometime later, to reuse the stored filehandles my $fh = $nbdc_filehandles[$idx]; my $line = <$fh>; # ...
In reply to Re: Using a filehandle tucked into an array
by almut
in thread Using a filehandle tucked into an array
by redbeard
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |