- 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程序設計(慕課版)
- Microsoft Exchange Server PowerShell Cookbook(Third Edition)
- 數據庫原理及應用(Access版)第3版
- R語言游戲數據分析與挖掘
- 面向STEM的Scratch創新課程
- C語言程序設計同步訓練與上機指導(第三版)
- Python機器學習基礎教程
- Flutter跨平臺開發入門與實戰
- SQL 經典實例
- 計算機應用基礎案例教程
- Learning AWS
- 區塊鏈架構之美:從比特幣、以太坊、超級賬本看區塊鏈架構設計
- Emotional Intelligence for IT Professionals
- Building Business Websites with Squarespace 7(Second Edition)
- Mobile Forensics:Advanced Investigative Strategies