标题: BEGIN 和 END [打印本页] 作者: beyes 时间: 2011-10-20 13:57 标题: BEGIN 和 END Perl 和 awk 一样,也有 BEGIN 和 END 模式。
BEGIN 表示在子程序的开头立刻执行。如果提供了多个 BEGIN,那么按照它们定义的顺序依次执行。
END 在所有任务完成后执行,甚至在通过 die 函数退出程序时也是如此,如果提供了多个 END,那么按照它们定义的顺序依次执行。
测试代码:
[code=perl]#!/usr/bin/perl
sub myfunc {
chdir ("/root") || die "Can't cd to /root: $!\n";
}
BEGIN { print "This execute first\n"};
END { print "The line number at here is:" , __LINE__ , "\n"};
myfunc[/mw_shl_code]
运行输出:
$ ./beginend.pl
This execute first
Can't cd to /root: Permission denied
The line number at here is:7