perl - 当设置 Perl 代码作为脚本或模块运行时,__PACKAGE__ 的原因是什么?

标签 perl module

在这个 earlier Stackoverflow question尤其是 brian d foy's "How a Script Becomes a Module"我已经阅读了如何设置代码,以便它可以作为脚本或模块运行,使用这种技术:

package SomeModule;

__PACKAGE__->run(@ARGV) unless caller();

sub run {
    # Do stuff here if you are running the file as
    # a script rather than a module.
}
__PACKAGE__的目的是什么在这个设置中?为什么不这样做呢?
run(@ARGV) unless caller();

最佳答案

如果你说 __PACKAGE__->run(@ARGV)然后 run可以在您继承的类中定义,也可以允许类从该类继承。如果你只是说run(@ARGV)您缺少类(class)信息。这仅在您进行 OO 风格编程时才重要。

将以下内容放入名为 Foo.pm 的文件中,然后说 perl Foo.pm 1 2 3

package Foo;

use strict;
use warnings;

__PACKAGE__->main(@ARGV) unless caller;

sub main {
    my $class = shift;
    my $obj   = $class->new(@ARGV);
    print $obj->to_string, "\n";
}

sub new {
    my $class = shift;
    return bless [@_], $class;
}

sub to_string {
    my $self = shift;
    return "args: " . join ", ", map { "[$_]" } @$self;
}

1;

现在将以下内容放入 Bar.pm ,然后说 perl Bar.pm a b c .
package Bar;

use strict;
use warnings;

use base 'Foo';

__PACKAGE__->main(@ARGV) unless caller;

sub to_string {
    my $self = shift;
    return "args: " . join ", ", map { "<$_>" } @$self;
}

1;

现在让我们看看如果你不使用 __PACKAGE__ 会发生什么在这种环境下。在 Foo.pm 中制作第一段代码看起来像这样:
main(@ARGV) unless caller;

sub main {
    my $obj = Foo->new(@ARGV);
    print $obj->to_string, "\n";
}

现在运行 perl Foo.pm 1 2 3 .一切都应该看起来正确。现在尝试运行 perl Bar.pm a b c .我们仍然得到输出,但这不是我们期望的输出。如果我们删除 __PACKAGE__ 会发生什么来自 Bar.pm ?好吧,我们得到错误:Undefined subroutine &Bar::main called at Bar.pm line 8.这是因为没有main模块中的函数,我们没有用类调用它,所以它不会在 Foo 中查找它包了。

关于perl - 当设置 Perl 代码作为脚本或模块运行时,__PACKAGE__ 的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1215657/

相关文章:

perl - 如何使用外部数据过滤 DBIX::Class 结果集?

perl - 如何在 Perl 中获取文件的确切完整路径

perl - Cairo::SolidPattern 不是 GooCanvas2::CairoPattern 类型

perl - Perl 5 和 Perl 6 中的 Unicode 属性 "Space"

python - 我如何 'force' python 使用特定版本的模块?

vb.net - VB 模块中的公共(public)属性 - 跨客户端行为

Ruby 尝试访问表兄弟类中的模块变量

python - 如何在每次更改后无需重新启动解释器的情况下开发 Python 模块/包?

perl - 如何使用 perl 脚本读取服务器上的文件

excel - 如何使用 VBA 导出工作表按钮和详细信息