Course of Raku / Advanced / Control flow
Phasers
A phaser is a special block that runs automatically at a particular moment in the life of a program, rather than where it appears in the source code. You do not call a phaser; you only say when its code should run, by naming the block.
The most common phasers mark stages of the program as a whole:
BEGINruns as early as possible, while the program is still being compiled;INITruns once at the start of the run, before the main code;ENDruns once at the very end, after the main code has finished.
The following program places these phasers among ordinary statements. Notice that the output does not follow the order of the lines in the file:
say 'main body';
BEGIN say 'BEGIN';
END say 'END';
INIT say 'INIT';The program prints:
BEGIN
INIT
main body
ENDBEGIN runs first, during compilation. Then, at run time,
INIT runs before the main body. The main body prints next,
and END runs last, no matter where it was written.
A common use of END is to print a summary or clean
something up just before the program exits, while BEGIN is
handy for work that must happen before anything else.
Practice
Complete the quiz that covers the contents of this topic.
Exercises
This section contains 3 exercises. Examine all the topics of this section before doing the coding practice.
Course navigation
← Control flow | Final message →