in reply to Using an IO::File object stored in a Hash.
G'day jjs04,
Welcome to the Monastery.
"What am I missing? I suspect it is something quite simple that I have not experienced before."
Yes, it's fairly simple (once you know about it). You just need to put the filehandle in a block, e.g.
close { $hash{'handle'} };
Update (correction): Firstly, I saw the close and thought that was the problem: ++BrowserUk has correctly identified the issue and provided a fix. Secondly, while I was certain your close (as written) was a problem, I can't reproduce it: perhaps it was a problem in older versions of Perl (I tried in 5.24.0 and 5.14.0). Thirdly, the close statement I wrote won't work as is: you'll get an "Odd number of elements in anonymous hash" message. If you do need a block (for your version of Perl), you'll need to prefix it with a '*'. Apologies for the misinformation and any confusion I may have caused. Here's how to write both a print and a close (using a block) without any warning or error messages:
print { $hash{'handle'} } "...\n"; close *{ $hash{'handle'} };
That issue doesn't appear to be mentioned in the close doco:
it probably should be!
However, the print doco does mention the same issue:
"If you're storing handles in an array or hash, or in general whenever you're using any expression more complex than a bareword handle or a plain, unsubscripted scalar variable to retrieve it, you will have to use a block returning the filehandle value instead, ..."
Update (additional information): The close block issue was niggling me, so I did some further research. As already stated, I couldn't reproduce any problem with 5.24.0 or 5.14.0 (the newest and oldest versions, respectively, that I have installed locally). I looked in the earliest (5.8.8) online perldoc, http://perldoc.perl.org/5.8.8/functions/close.html: no mention there. I then looked in the earliest (5.004) I could find on CPAN, http://search.cpan.org/~chips/perl5.004/pod/perlfunc.pod#close_FILEHANDLE (dated 15 May 1997): no mention there either. So, it seems there's no reference to this in the past two decades and it appears that I was simply wrong about that. I was probably thinking of the print block requirement, as per the documentation link, and quote, above. Again, my apologies.
— Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Using an IO::File object stored in a Hash.
by jjs04 (Novice) on Jan 20, 2017 at 17:10 UTC | |
by stevieb (Canon) on Jan 20, 2017 at 17:54 UTC | |
by kcott (Archbishop) on Jan 21, 2017 at 01:43 UTC |