佩尔莫德问题

发布于 2024-11-30 11:19:53 字数 227 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风铃鹿 2024-12-07 11:19:53

如果您需要在编译时而不是运行时执行某些代码,则只需要一个BEGIN块。

示例:假设您在非标准库目录(例如 /tmp)中有一个模块 Foo.pm。您知道可以通过修改 @INC 以包含 /tmp 来让 perl 找到该模块。然而,这是行不通的:

unshift(@INC, '/tmp');
use Foo;    # perl reports Foo.pm not found

问题是 use 语句是在编译时执行的,而 unshift 语句是在运行时执行的,所以当 perl 查找 >Foo.pm,包含路径尚未修改(尚未)。

实现此目的的正确方法是:

BEGIN { unshift(@INC, '/tmp') };
use Foo;

现在 unshift 语句在编译时且在 use Foo 语句之前执行。

绝大多数脚本不需要 BEGIN 块。 BEGIN 块中需要的很多内容都可以通过 use-ing 其他模块来获得。例如,在这种情况下,我们可以使用 lib.pm 模块确保 /tmp 位于 @INC 中:

use lib '/tmp';
use Foo;

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:

unshift(@INC, '/tmp');
use Foo;    # perl reports Foo.pm not found

The problem is that the use statement is executed at compile time whereas the unshift statement is executed at run time, so when perl looks for Foo.pm, the include path hasn't been modified (yet).

The right way to accomplish this is:

BEGIN { unshift(@INC, '/tmp') };
use Foo;

Now the unshift statement is executed at compile-time and before the use Foo statement.

The vast majority of scripts will not require BEGIN blocks. A lot of what you need in BEGIN blocks can be obtained through use-ing other modules. For instance, in this case we could make sure /tmp is in @INC by using the lib.pm module:

use lib '/tmp';
use Foo;
高冷爸爸 2024-12-07 11:19:53

模块中的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文