這是5個特殊的代碼塊。要理解這幾個塊,關鍵在於幾個時間點:ui
在BEGIN期間能夠作一些程序執行以前的操做,例如事先給某個比較特殊的變量賦值,檢查文件是否存在,檢查操做系統是否知足要求等等。操作系統
package Foo; use strict; use warnings; BEGIN { print "This is the first BEGIN block\n"; } print "The program is running\n"; BEGIN { print "This is the second BEGIN block\n"; }
因爲BEGIN代碼塊在編譯期間執行,程序普通行的print是在執行期間執行,因此上面的代碼結果爲:code
This is the first BEGIN block This is the second BEGIN block The program is running
下面程序出現語法錯誤,但BEGIN也會執行:it
BEGIN { print "This is the first BEGIN block\n"; } print "The program is running\n"; BEGIN { print "This is the second BEGIN block\n"; } my $x =;
執行結果:io
syntax error at some_program.pl line 8, near "=;" Execution of some_program.pl aborted due to compilation errors. This is the first BEGIN block This is the second BEGIN block
不過上面的error信息不必定會最早輸出,由於stdout和stderr是兩個獨立的文件句柄,沒法保證它們之間的順序。編譯
實際上,use導入模塊時若是導入的是空列表,它等價於在BEGIN中使用require語句:ast
use File::Find (); # 等價於 BEGIN { require File::Find; }
END塊是在程序執行結束,但退出前執行的,也就是上面的步驟(3)所在期間。require
END { print "This is the first END block\n"; } END { print "This is the second END block\n"; }
輸出結果:注意,先輸出second END,再輸出first END變量
This is the second END block This is the first END block
INIT、CHECK 和 UNITCHECK 塊生效於程序編譯結束以後、執行以前。因此若是語法錯誤,它們不會被觸發。perl
INIT { print "This is the first INIT block\n"; } CHECK { print "This is the first CHECK block\n"; } INIT { print "This is the second INIT block\n"; } CHECK { print "This is the second CHECK block\n"; }
輸出結果:
This is the second CHECK block This is the first CHECK block This is the first INIT block This is the second INIT block