When creating a program in Perl 6, it is important to understand that controlling the program flow is a little trickier than simply following the instructions of the code. There are special types of code blocks that are automatically called by the compiler at different phases of the compilation and the execution processes. Those blocks are called phasers.
We mentioned two of them, BEGIN and CHECK, in Chapter 1,What is Perl 6?, when we talked about the -c command-line option of the compiler. Now, let's take a look at the rest.
Syntactically, phasers are blocks of code in curly braces preceded by a phaser name. The following table summarizes the different phasers that exist in Perl 6. Some of the phasers are executed at compile-time before the rest of the program is compiled and executed. Some are called at runtime.
Let's expand the 'Hello, World!' program and add a few phasers to it:
BEGIN {
say 'BEGIN 1';
}
END {
say 'END';
}
say 'Hello, World!';
BEGIN {
say 'BEGIN 2';
}
CHECK {
say 'CHECK';
}
INIT {
say 'INIT';
}
This code produces the following output:
BEGIN 1
BEGIN 2
CHECK
INIT
Hello, World!
END
In this example, please pay attention to a couple of characteristics of the phaser blocks. There are two BEGIN blocks here, and they are executed in the order they appear in the source code. Also, the actual position of the block is not always important. For example, the END block is located before the main program but is executed after it. Similarly, the second BEGIN block and the CHECK and INIT blocks are located after the main program but are called before it.
Phasers are good candidates that can do some work when the program is about to start or finish. For example, you may check if the program is running in the correct environment with the BEGIN block. In the END block, you may close all open files or print something to the log before the program quits.
In Chapter 10, Working withExceptions, we will work with another two phasers—CATCH and CONTROL.
There are many more phasers in Perl 6 that help to organize hooks during the program execution, such as ENTER and LEAVE that are called when the flow of the program enters or leaves a block of code. For a detailed description of those phasers, refer to the documentation page at docs.perl6.org/language/phasers.