众所周知,Perl中的BEGIN块在其它代码执行前执行,而END块在其它代码执行后执行。
可是,如果Perl脚本中同时包含多个BEGIN及END块呢,其执行情况如何?
看下面测试代码:
#!/usr/bin/perl -w
use strict;
END{ print "the [" . __LINE__ . "] end block\n"; }
print "The other [" . __LINE__ . "] logical\n";
BEGIN{ print "the [" . __LINE__ . "] begin block\n"; }
print "The other [" . __LINE__ . "] logical\n";
END{ print "the [" . __LINE__ . "] end block\n"; }
print "The other [" . __LINE__ . "] logical\n";
BEGIN{ print "the [" . __LINE__ . "] begin block\n"; }
print "The other [" . __LINE__ . "] logical\n";
END{ print "the [" . __LINE__ . "] end block\n"; }
print "The other [" . __LINE__ . "] logical\n";
BEGIN{ print "the [" . __LINE__ . "] begin block\n"; }
print "The other [" . __LINE__ . "] logical\n";
执行结果如下:
$./p.pl
the [5] begin block
the [9] begin block
the [13] begin block
The other [4] logical
The other [6] logical
The other [8] logical
The other [10] logical
The other [12] logical
The other [14] logical
the [11] end block
the [7] end block
the [3] end block
根据多次执行情况来看,其执行结果是唯一的,即可以认为不存在随机顺序的问题。
那么根据上面执行结果:
1、多个BEGIN块按照在脚本中出现的顺序,自上向下执行。
2、多个END块按照在脚本中出现的顺序,自下而上执行。
上述结论为实验结果,暂无官方信息佐证。