The following bit of code surprised me:

#!/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" }
The output:
# 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.

blyman
setenv EXINIT 'set noai ts=2'

Fixed 'readmore' - dvergin 2003-06-27


In reply to Execution order of END/CHECK vs BEGIN/INIT by belden

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.