Chinaunix首页 | 论坛 | 博客
  • 博客访问: 988888
  • 博文数量: 150
  • 博客积分: 3017
  • 博客等级: 少校
  • 技术积分: 3829
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-19 14:40
个人简介

Now in Baidu WISE team

文章分类

全部博文(150)

文章存档

2014年(8)

2013年(31)

2012年(111)

分类: Python/Ruby

2012-02-12 18:49:26

In perl, there are 4 special subroutines, which will be executed automatically by the compilation process and the execution process. The key word "sub" is optional when defining those subroutines.
 

1. BEGIN() -  It will be called before compile. And because all code has not been load, you cannot use any variable defined in the code. Only some default variables about the package is avaliable. 

2. CHECK() - Called at the end of the compilation process.

3. END() - Called at the end of the execution process.

Whatever the complation process success or fail, the 3 subroutines will be executed. And all varibales and resources defined in code are not available. Only perl own variables are availale, such as "__PACKAGE__"

 

4. INIT() - Called at the beginning of the execution process.

In INIT, you can use variables defined in code.

 

See the example:

There are only 2 sentences in main. I defined a scalar $f and output a sentence.

If there are syntx error in the 2 sentences, you will find that BEGIN, CHECK, END are executed, and 'Use of uninitialized value $f in concatenation (.) or string' is reported. The execution order is BEGIN->CHECK->END.

 

If there is not errors, 4 subroutines will be excuted. INIT is executed between CHECK and END. Also, $f is uninitialized in BEGIN, CHECK and END. But $f is available in INIT. The execution order is BEGIN->CHECK->INIT->END

 

  1. $f = "resource";
  2. print("show you BEGIN CHECK END INIT \n");
  3. BEGIN {
  4.     print("In BEGIN: name space = ",__PACKAGE__,"\n");
  5.     #$f is not available here
  6.     print("In BEGIN: \$f = $f...\n");
  7. }     
  8. CHECK {
  9.     print("In CHECK: name space = ",__PACKAGE__,"\n");
  10.     #$f is not available here
  11.     print("In CHECK: \$f = $f...\n");
  12. }     
  13. INIT {
  14.     print("In INIT: name space = ",__PACKAGE__,"\n");

  15.     #$f is avaiblable
  16.     print("In INIT: \$f = $f...\n");
  17. }
  18. END {
  19.     print("In END: name space = ",__PACKAGE__,"\n");
  20.     #$f is not available here
  21.     print("In END: \$f = $f...\n");
  22. }
Reference:
阅读(874) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~