- 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.
- 大學計算機應用基礎實踐教程
- Java高并發核心編程(卷2):多線程、鎖、JMM、JUC、高并發設計模式
- 數據結構和算法基礎(Java語言實現)
- Visual Basic程序設計(第3版):學習指導與練習
- Getting Started with PowerShell
- SAS數據統計分析與編程實踐
- C# 8.0核心技術指南(原書第8版)
- Learning Nessus for Penetration Testing
- Java設計模式深入研究
- Mastering ASP.NET Web API
- Mastering Machine Learning with scikit-learn
- JavaScript全棧開發
- 精通Oracle 12c 數據庫管理
- 梔子貓的奇幻編程之旅:21天探索信息學奧賽C++編程
- 跟著迪哥學Python數據分析與機器學習實戰