[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Omaha.pm] Debugging running Perl code on Windows.



-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1


On Sep 21, 2004, at 9:22 AM, Daniel Linder wrote:
> ObPerlNote: The "END" directive is great for this -- I just found this
> about two months ago and really like this "catch all" for the
> termination of my scripts.

<quote who="Jay Hannah">
> How does that work?

Glad you asked... ;)

If you've ever written a perl script with multiple possible exit locations
you've probably written some sort of cleanup-code and tried to call it
right before the actual "exit" or "die" command.  But what happens if your
script dies unexpectedly at someother point in the code?

This is where the END "package destructor" comes into play.  Just add code
like the following to your program and it will execute the code as the
last steps when exiting.

Say you had a logfile you wanted to cleanup after each successfull run,
but your code has many exit points.  Rather than trying to find all the
exit points and put in your cleanup subroutines -- say
"WriteFinalInfoToLogFile()" -- then call "close(LOGFILE)", then finally
"exit" (with the apropriate exit code for that section).

You can do this instead:

END {
    WriteFinalInfoToLogFile();
    close(LOGFILE);
}

When a branch of your code wants to exit with code "0", the "exit 0" is
called, the END section is envoked, and finally the "exit 0" is completed
and the program drops back to the shell with an exit code of 0 (normally
an "OK" signal).

When another branch wants to exit with "code 1" (an error or other
meaning), the "exit 1" is called, the END section is envoked, and finally
the "exit 1" is completed and the program drops back to the shell, but
this time the "exit code" of the program is set to 1.

Clear? :)

Check out "http://www.perl.com/doc/manual/html/pod/perlmod.html"; or
"http://www.perldoc.com/perl5.8.0/pod/perlmod.html";

I read somewhere that the order in which the END statements are called
*is* important -- some modules may use them for their own cleanup.  They
are run in the reverse order as the Perl interperter sees them.  If you
want yours to run at the very end after all the other modules have done
their cleanup, then you will need to place your END { } block at the head
of your program, before all other "use" or "include" statements.

Dan

- - - - -
"I do not fear computer,
I fear the lack of them."
 -- Isaac Asimov

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQFBUG+GNiBNyqUzGb8RAgIMAJsFtckKsEElou/2ngkPRruFG0fANACfWN6X
kyM51IUfF9l0L33u3reeXlM=
=4tMq
-----END PGP SIGNATURE-----