官术网_书友最值得收藏!

Phasers

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 with Exceptions, 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.

主站蜘蛛池模板: 台东县| 平南县| 建始县| 昔阳县| 威宁| 金塔县| 定南县| 永吉县| 蒙自县| 湘潭县| 包头市| 蓝田县| 吉首市| 桦川县| 清水县| 含山县| 泸西县| 墨竹工卡县| 辰溪县| 新疆| 鲁甸县| 丹棱县| 庆城县| 思茅市| 昭通市| 岫岩| 伊金霍洛旗| 滕州市| 玉溪市| 岚皋县| 清水县| 康定县| 福贡县| 普安县| 淳化县| 合山市| 华宁县| 通渭县| 资中县| 丹巴县| 长乐市|