The following bit of code surprised me:
The output:#!/usr/bin/perl BEGIN { print "1st BEGIN\n" } BEGIN { print "2nd BEGIN\n" } BEGIN { print "\n" } INIT { print "1st INIT\n" } INIT { print "2nd INIT\n" } INIT { print "\n" } CHECK { print "1st CHECK\n" } CHECK { print "2nd CHECK\n" } CHECK { print "\n" } print "1st code\n" ; print "2nd code\n" ; print "\n" ; exit; END { print "1st END\n" } END { print "2nd END\n" } END { print "\n" }
# begin output - this line not really printed by code above 1st BEGIN 2nd BEGIN 2nd CHECK 1st CHECK 1st INIT 2nd INIT 1st code 2nd code 2nd END 1st END # end output - this line not really printed by code above
perlmod explains why we see "2nd CHECK" and "2nd END" before "1st CHECK" and "1st END":
You may have multiple END blocks within a file--they will execute in reverse order of definition; that is: last in, first out (LIFO)...Similar to END blocks, CHECK blocks are run just after the Perl compile phase ends and before the run time begins, in LIFO order.
perlmod also explains that BEGIN and INIT blocks are executed in first in, first out (FIFO) order.
But why do BEGIN and INIT blocks happen in FIFO order, and CHECK and END blocks happen in LIFO order? This is obviously a conscious design decision in the language- and must be better than all happening in FIFO order(0).
So, what gives? Any insight?
(0) - I say "must be better" because making END happen in LIFO order using -n or -p flags is referred to as a "degenerate case" by perlmod.
Fixed 'readmore' - dvergin 2003-06-27
In reply to Execution order of END/CHECK vs BEGIN/INIT by belden
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |