BEGIN语句块

BEGIN语句块在perl完成解析该块的时候被执行,甚至在文件其他代码被解析之前。在执行的时候会被忽略:

 
  
  1. use strict;  
  2. use warnings;  
  3.  
  4. print "This gets printed second";  
  5.  
  6. BEGIN {  
  7.     print "This gets printed first";  
  8. }  
  9.  
  10. print "This gets printed third"; 

BEGIN块一般首先被执行。你可以创建多个BEGIN块(但是最好不要),它们被从头到尾的执行。BEGIN块通常被第一个执行即使它是在脚本的中间(但不要这样做)或者在最后(也不要这样做)。不要把它混在正常代码里面。吧BEGIN块放在开头!

BEGIN块会在该块被解析的时候就执行。当完成后,解析会回到BEGIN块末尾继续往下解析。只有当整个脚本或者模块被解析后,BEGIN块之外的代码就会被执行。

 
  
  1. use strict;  
  2. use warnings;  
  3.  
  4. print "This 'print' statement gets parsed successfully but never executed";  
  5.  
  6. BEGIN {  
  7.     print "This gets printed first";  
  8. }  
  9.  
  10. print "This, also, is parsed successfully but never executed";  
  11.  
  12. ...because e4h8v3oitv8h4o8gch3o84c3 there is a huge parsing error down here. 

因为它们在编译的时候就会被执行,BEGIN块放在条件块里面也会首先被执行,即使条件判断是false,不管条件判断是否被执行,实际上永远不会去判断:

 
  
  1. if(0) {  
  2.     BEGIN {  
  3.         print "This will definitely get printed";  
  4.     }  
  5.     print "Even though this won't";  

不要把BEGIN块放在条件判断语句内。如果你要在某些条件下才执行,你需要把条件判断放在BEGIN块里面:

 
  
  1. BEGIN {  
  2.     if($condition) {  
  3.         # etc.  
  4.     }