Perl中BEGIN语句块
BEGIN语句块BEGIN语句块在perl完成解析该块的时候被执行,甚至在文件其他代码被解析之前。在执行的时候会被忽略:
[*]use strict;
[*]use warnings;
[*]
[*]print "This gets printed second";
[*]
[*]BEGIN {
[*] print "This gets printed first";
[*]}
[*]
[*]print "This gets printed third";
BEGIN块一般首先被执行。你可以创建多个BEGIN块(但是最好不要),它们被从头到尾的执行。BEGIN块通常被第一个执行即使它是在脚本的中间(但不要这样做)或者在最后(也不要这样做)。不要把它混在正常代码里面。吧BEGIN块放在开头!
BEGIN块会在该块被解析的时候就执行。当完成后,解析会回到BEGIN块末尾继续往下解析。只有当整个脚本或者模块被解析后,BEGIN块之外的代码就会被执行。
[*]use strict;
[*]use warnings;
[*]
[*]print "This 'print' statement gets parsed successfully but never executed";
[*]
[*]BEGIN {
[*] print "This gets printed first";
[*]}
[*]
[*]print "This, also, is parsed successfully but never executed";
[*]
[*]...because e4h8v3oitv8h4o8gch3o84c3 there is a huge parsing error down here.
因为它们在编译的时候就会被执行,BEGIN块放在条件块里面也会首先被执行,即使条件判断是false,不管条件判断是否被执行,实际上永远不会去判断:
[*]if(0) {
[*] BEGIN {
[*] print "This will definitely get printed";
[*] }
[*] print "Even though this won't";
[*]}
不要把BEGIN块放在条件判断语句内。如果你要在某些条件下才执行,你需要把条件判断放在BEGIN块里面:
[*]BEGIN {
[*] if($condition) {
[*] # etc.
[*] }
[*]}
页:
[1]