Phasers
BEGIN & END
FullRun code at compile time (BEGIN) or at program exit (END).
A phaser is a block that runs at a particular moment in a program's life, not where it is written. BEGIN fires at compile time — as soon as it is parsed — and END fires once, as the program shuts down.
BEGIN — at compile time #
BEGIN runs during compilation, before any run-time code, so its output appears first regardless of position.
BEGIN say "compile-time"; say "run-time";
Output
compile-time
run-timeBEGIN as a value #
BEGIN also produces a value, computed once at compile time and frozen into the program — useful for constants.
my $t = BEGIN { 2 * 21 };
say $t;
Output
42END — at exit #
END runs when the program finishes, after the main body — even if the END block is written first.
say "body"; END say "at exit";
Output
body
at exitNotes #
- Because
BEGINruns at compile time, anything it references must already be available then; it is the mechanism behindconstantand compile-timeuseeffects. - Multiple
ENDblocks run in reverse order of definition (last defined, first run), like a stack of cleanups. INITis the run-time cousin ofBEGIN: it runs once, at the start of execution rather than during compilation.