加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl中BEGIN语句块

发布时间:2020-12-16 00:15:47 所属栏目:大数据 来源:网络整理
导读:? BEGIN语句块 BEGIN语句块在perl完成解析该块的时候被执行,甚至在文件其他代码被解析之前。在执行的时候会被忽略: use?strict; ? use?warnings; ? ? print?"This?gets?printed?second"; ? ? BEGIN?{ ? ????print?"This?gets?printed?first"; ? } ? ? prin

?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"; ?
  6. }?

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读