dbaad has asked for the wisdom of the Perl Monks concerning the following question:

Is there a generic way to close all open filehandles from a sub routine without having to name them?

I want to have a subroutine that I can call from anywhere in my script that I will use to handle errors and then exit. The problem is....at any one point, I might have a variety of filehandles open for log files, config files, whatever.

Rather than specifying to close them all by name in the sub, is there a way to close them all generically, or is it even necessary?

Any knowledge shared is surely appreciated!

Replies are listed 'Best First'.
Re: filehandle cleanup
by Zaxo (Archbishop) on May 04, 2004 at 21:37 UTC

    Not necessary, perl closes them gracefully on exit.

    After Compline,
    Zaxo

Re: filehandle cleanup
by geekgrrl (Pilgrim) on May 04, 2004 at 22:37 UTC
    I also believe that if your file handles are of the type
    open my $in, "$filename" or die "$filename";
    it will automatically close when you leave the scope of the variable $in.
    just thought I would offer that up as well.
Re: filehandle cleanup
by Corion (Patriarch) on May 05, 2004 at 06:32 UTC

    In addition to what was said above, there also is the temporary assignment possible with local, which will also close your file handles as soon as they go out of scope:

    sub scan_file { my ($filename) = @_; local *FILE; open FILE, "< $filename" or die "couldn't read '$filename': $!"; return grep { ! /^#/ } FILE; # Perl closes FILE here };

    But if you're already using Perl 5.8.x and don't need your script to run under 5.005, use the three argument open and the lexical filehandle as proposed by geekgrrl above.

Re: filehandle cleanup
by Belgarion (Chaplain) on May 04, 2004 at 21:39 UTC

    Unless I'm seriously mistaken, when the perl interpreter closes, all your open file handles will be closed. I know this is true for Unix and I'm almost positive it's true under Windows. When the script exits any open file handles are automatically closed.

      Thanks for the replies. Easy for me then.....no need to close them if I'm exiting.