Why does Perl run END and CHECK blocks in LIFO order?
I have no deep or interesting question-开发者_JAVA技巧-I'm just curious why it is so.
Each package is assumed to rely on the correct function of EVERYTHING that went before it. END blocks are intended to "clean up and close out" anything the package might need to take care of before the program finishes. But this work might rely on the correct functioning of the packages started earlier, which might no longer be true if they are allowed to run their END blocks.
If you did it any other way, there could be bad bugs.
Here is a simple example which may help:
# perl
BEGIN { print "(" }
END { print ")" }
BEGIN { print "[" }
END { print "]" }
This outputs: ([])
If END
had been a FIFO then BEGIN/END
wouldn't work well together.
Update - excerpt from Programming Perl 3rd edition, Chapter 18: Compiling - Avant-Garde Compiler, Retro Interpreter, page 483:
If you have several END blocks within a file, they execute in reverse order of their definition. That is, the last END block defined is the first one executed when your program finishes. This reversal enables related BEGIN and END blocks to nest the way you'd expect, if you pair them up
/I3az/
Perl borrows heavily from C, and END
follows the lead of C's atexit
:
NAME
atexit - register a function to run at process termination
SYNOPSIS
#include <stdlib.h> int atexit(void (*func)(void));
DESCRIPTION
The
atexit()
function shall register the function pointed to byfunc
, to be called without arguments at normal program termination. At normal program termination, all functions registered by theatexit()
function shall be called, in the reverse order of their registration …
精彩评论