佩尔莫德问题
在 perlmod/Perl 模块 中的示例中,有一个 BEGIN块。我查看了一些模块,但没有一个有
BEGIN
块。在编写模块时我应该使用这样的 BEGIN
块吗?还是它是可有可无的?
In the example in perlmod/Perl Modules there is a BEGIN
block. I looked at some modules but none of these had a BEGIN
block. Should I use such a BEGIN
block when writing a module or is it dispensable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要在编译时而不是运行时执行某些代码,则只需要一个
BEGIN
块。示例:假设您在非标准库目录(例如
/tmp
)中有一个模块Foo.pm
。您知道可以通过修改@INC
以包含/tmp
来让 perl 找到该模块。然而,这是行不通的:问题是
use
语句是在编译时执行的,而unshift
语句是在运行时执行的,所以当 perl 查找>Foo.pm
,包含路径尚未修改(尚未)。实现此目的的正确方法是:
现在
unshift
语句在编译时且在use Foo
语句之前执行。绝大多数脚本不需要
BEGIN
块。BEGIN
块中需要的很多内容都可以通过use
-ing 其他模块来获得。例如,在这种情况下,我们可以使用lib.pm
模块确保/tmp
位于@INC
中:You only need a
BEGIN
block if you need to execute some code at compile time versus run-time.An example: Suppose you have a module
Foo.pm
in a non-standard library directory (like/tmp
). You know you can have perl find the module by modifying@INC
to include/tmp
. However, this will not work:The problem is that the
use
statement is executed at compile time whereas theunshift
statement is executed at run time, so when perl looks forFoo.pm
, the include path hasn't been modified (yet).The right way to accomplish this is:
Now the
unshift
statement is executed at compile-time and before theuse Foo
statement.The vast majority of scripts will not require
BEGIN
blocks. A lot of what you need inBEGIN
blocks can be obtained throughuse
-ing other modules. For instance, in this case we could make sure/tmp
is in@INC
by using thelib.pm
module:模块中的 BEGIN 块是完全可有可无的。仅当模块在加载时、使用之前必须完成某些操作时,才使用它。很少有理由在此时做太多事情,因此也很少有理由使用 BEGIN 块。
A BEGIN block in a module is entirely dispensable. You only use it if there is something that must be done by your module when it is loaded, before it is used. There are seldom reasons to do much at that point, so there are seldom reasons to use a BEGIN block.