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

Hi people.

I have a script that, for example, opens a output log file at the start of its execution. If the script should die at any stage (bad parameters, cant find file..) is there a close function that will close any files I had opened?

Example

#!/perl open (DEBUG, ">> /tmp/debug.log"); if (!$ARGV[0]){ die "no arguments!"; } else{ print "hello\n"; } close DEBUG;

if there are no params supplied, the script will die, and the file won't have been closed.. is there an END {} sub?

Replies are listed 'Best First'.
Re: Cleaning up a script
by lestrrat (Deacon) on Aug 20, 2001 at 09:46 UTC

    As jryan points out, perl closes all open filehandles at the end of the script.

    If you want to do some elaborate handling in case of run time errors ( such as die and croak ) you can either:

    # use eval eval{ # your code here }; if( $@ ) { # error handling code here } # ... or use $SIG{ __DIE__ } $SIG{ __DIE__ } = sub{ # error handling code here } # your code here

    Since $SIG{ __DIE__ } is sort of handled like any other signals, you can specify the value of $SIG{ __DIE__ } just like you specify other signal handlers

Re: Cleaning up a script
by jryan (Vicar) on Aug 20, 2001 at 07:26 UTC

    No, but theres an end block. It does exactly what you expect, executing the block and the end of the program. Like so:

    END { print "I'm at the end!"; close (DEBUG); }

    Btw, I think perl automatically closes files when a program has finished execution.

Re: Cleaning up a script
by perrin (Chancellor) on Aug 21, 2001 at 04:18 UTC
    You can use IO::File to create file handles that automatically close when they go out of scope. There's some info on this at perldoc -f open.