http://qs321.pair.com?node_id=376757


in reply to When do filehandles close?

A filehandle will bet closed when:

  1. It is formally closed with close
  2. When it goes out of scope which occurs:
    1. If it is localised to a block and you exit said block, provided no closure of course
    2. When the program exits everything goes out of scope.

Examples, no or die $! for clarity not form.

open F, $file; close F; # F is closed { open my $fh, $file; } # $fh is closed open F, $file; exit 0; # program is gone and F is closed # closure { my $fh; sub append { unless ( $fh ) { open $fh, $file } } } # closure means $fh is not destroyed, $fh remains open until program e +xit

cheers

tachyon

Replies are listed 'Best First'.
Re^2: When do filehandles close?
by pg (Canon) on Jul 23, 2004 at 00:04 UTC

    Missed one little thing;-) as the OP already pointed out, reopen implicitly close a file handler.

    However in this case $. (current line number for the last filehandle accessed) is not reset. I would prefer explicit close all the time simply because of this.

    Update

    Just add a piece of code for demon (name this script a.pl):

    use strict; use warnings; open(SCRIPT, "<", "a.pl"); <SCRIPT>; <SCRIPT>; print $., "\n"; #close(SCRIPT); open(SCRIPT, "<", "a.pl"); <SCRIPT>; print $., "\n";

    Try to comment or uncomment that close. If it is commented, print out:

    2 3

    If it is not commented:

    2 1