A BEGIN block will run because those run at compilation time and require drops Perl back into the compiler.

Likewise an END block will run because that phase hasn't yet occurred when the require is executing.

However CHECK, which runs (to quote perlmod) "after the initial Perl compile phase", and INIT blocks, which run "just before the Perl runtime begins execution", are not executed since their triggers (post-initial compile phase and prior to the runtime starting) have already passed. But when they're encountered during a BEGIN block by virtue of the code being pulled in via use those phases haven't passed and hence they will be called.

$ perl -MSpoo -e 0 Spoo BEGIN Spoo CHECK Spoo INIT Spoo END $ perl -e 'require Spoo' Spoo BEGIN Spoo END $ cat Spoo.pm package Spoo; BEGIN { print "Spoo BEGIN\n"; } END { print "Spoo END\n"; } INIT { print "Spoo INIT\n"; } CHECK { print "Spoo CHECK\n"; } 1; __END__

Think of it this way: BEGIN and friends are kind of special event handler subs called by the Perl runtime. When the given event happens (compilation phase occurs, the runtime is about to start) the runtime looks into the module in question and if it has defined a handler for that event the runtime executes the corresponding sub. It's just that some of the events don't occur for require because they're one time only and that time's passed for the current execution.

Update: Slight pronoun and wording tweak in last paragraph.

The cake is a lie.
The cake is a lie.
The cake is a lie.


In reply to Re^3: use equivalent ? I suspect not... by Fletch
in thread use equivalent ? I suspect not... by Bloodnok

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.