在这个 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/