in reply to Re^5: Scoping question - will file handle be closed? ("global")
in thread Scoping question - will file handle be closed?

Technically I was right but it looks like the global depends on $fh and so becomes lexically inaccessible, although that isn't quite the same as being closed. So yes, I have learned something here, thanks.

One world, one people

  • Comment on Re^6: Scoping question - will file handle be closed? ("global")

Replies are listed 'Best First'.
Re^7: Scoping question - will file handle be closed? ("global")
by Corion (Patriarch) on Jul 29, 2015 at 10:46 UTC

    A "global" cannot become "lexically inaccessible". That's what "global" means.

    I think your basic misconception comes from the good old days of Perl 4 and Perl 5.005, where Perl did not have lexical filehandles. The global variables holding the data on filehandles were more or less identical to a string. But this has changed with Perl 5.6.1, which was released in 2003 I think.

      Perl 5.006_001 taught Perl itself how to do what was being done in vanilla Perl code before that. See Symbol for some remnants of that prior art.

      People were getting lexical file handles that worked just fine in Perl prior to 5.006_001 by doing things rather close to:

      my $fh = do { local *FH; \*FH };

      That is, use local to get Perl to create an extra GLOB, take a reference to that glob, then let local remove that GLOB from the symbol table so you have a GLOB that isn't global and will be destroyed based on lexical scope (and reference counting).

      Symbol actually jumps through more hoops than my one-line example above. But it used to be pretty darn close to that.

      - tye        

Re^7: Scoping question - will file handle be closed? ("global")
by tye (Sage) on Jul 29, 2015 at 13:58 UTC
    although that isn't quite the same as being closed

    So you still refuse to learn this. The code demonstrates that the handle is actually closed, despite your persistent denials. Becoming lexically inaccessible doesn't cause impacts on external programs. The output lines appearing in the given order:

    ls: write error End

    shows that the handle is indeed closed (causing bin/ls to complain) before the next statement of Perl is executed.

    The actual mechanism is that the lexical file handle contains a reference to a GLOB, which is the same data structure that Perl uses for global variables. But this GLOB is not a global variable because it isn't stored in a symbol table. Which means that when the lexical goes out of scope (and has no references), the lexical is destroyed which removes the last reference to the GLOB which then destroys the GLOB which also closes the file handle.

    There is no global variable involved (because to be a global variable it has to have global scope; that is the definition of a global variable). And it does get destroyed and it does get closed (it can be destroyed because it isn't a global variable).

    - tye