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

  • Perl 6 Deep Dive
  • Andrew Shitov
  • 416字
  • 2021-07-03 00:05:47

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.

主站蜘蛛池模板: 榆林市| 凤冈县| 股票| 德江县| 崇仁县| 汾阳市| 泸定县| 方山县| 边坝县| 淮安市| 湘西| 资溪县| 巴塘县| 甘肃省| 乾安县| 平塘县| 香港| 广南县| 轮台县| 泰宁县| 荆门市| 仙桃市| 福建省| 茶陵县| 永川市| 桐梓县| 达州市| 遂川县| 邯郸市| 宝兴县| 东兰县| 汝城县| 云梦县| 江城| 佛坪县| 丽水市| 斗六市| 呼伦贝尔市| 黄大仙区| 焦作市| 工布江达县|