Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Perl run END and CHECK blocks in LIFO order?

I have no deep or interesting question--I'm just curious why it is so.

like image 852
gvkv Avatar asked Aug 24 '10 10:08

gvkv


3 Answers

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.

like image 150
Ian Avatar answered Nov 11 '22 00:11

Ian


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/

like image 6
draegtun Avatar answered Nov 10 '22 22:11

draegtun


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 by func, to be called without arguments at normal program termination. At normal program termination, all functions registered by the atexit() function shall be called, in the reverse order of their registration …

like image 1
Greg Bacon Avatar answered Nov 11 '22 00:11

Greg Bacon