Laurent_R has asked for the wisdom of the Perl Monks concerning the following question:
I feel a bit stupid on this issue. I was answering on a French Perl forum to a question in which the poster was trying to use symbolic references to store a number of file handles. I told the OP to use an array or hash of handles instead and outlined the basic syntax for it. I could not test it because it was too dependent on the OP's environment.
The OP said that it did not work. So I wrote a little demonstration program as follows:
But the OP was right: this does not seem to be able to read anything from the two files.my @in_fh; my $count = 0; while (my $line = <DATA>) { chomp $line; open my $IN, "<", $line or die "Cannot open file $line $!"; $in_fh[$count] = $IN; $count++; } my $i = 0; while ($i < $count) { while (my $line = <{$in_fh[$i]}> ) { print $line; } $i++; } __DATA__ one.txt two.txt
I was able to work around the problem with the following syntax fix:
but I am still puzzled at the fact that:while (my $line = readline $in_fh[$i] ) {
does not work properly.while (my $line = <{$in_fh[$i]}>) {
When I check the content of $in_fh[$i], I get a glob: GLOB(0x60006f218), so this seems to be correct. But when trying to read the line, it returns the glob instead of the line from the file. I suspect that this is one case where the compiler is confused by the syntax and would need a hint about the syntax intent, but did not find a solution with the diamond <...> operator. I am fairly sure that I have already done something very similar with braces around the array element containing the file handle, but can't remember what it was exactly to get it to work. Any idea?
Update: fixed the off-by-one error mentioned by hdb, which was not in the original program, but added by mistake by me in the above code when slightly simplifying the code for the purpose of making it shorter for this post. (And, yes, I am using strictures.) Thanks hdb.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Using an array of file handles
by choroba (Cardinal) on Apr 22, 2016 at 11:22 UTC | |
by Laurent_R (Canon) on Apr 22, 2016 at 12:21 UTC | |
|
Re: Using an array of file handles
by hdb (Monsignor) on Apr 22, 2016 at 11:32 UTC | |
by Laurent_R (Canon) on Apr 22, 2016 at 12:34 UTC | |
|
Re: Using an array of file handles
by Athanasius (Archbishop) on Apr 22, 2016 at 13:34 UTC | |
by Laurent_R (Canon) on Apr 22, 2016 at 19:28 UTC |