Phasers

BEGIN & END

Full

Run 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-time

BEGIN 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
42

END — 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 exit

Notes #