从我读过的关于使用 Perl 模块的所有内容来看,基本用法是:
.pm
的模块文件扩展名,其中包括语句 package <name>
, 其中 <name>
是不带扩展名的模块的文件名。 use <name>;
. 我正在编写的应用程序有一个主要的代码脚本,它使用了大约 5 个模块。我忘记包含
package <name>
模块中的语句,但我的代码仍然可以正常运行 use <name>
陈述。我开始收到 Undefined subroutine
其中一个模块出错,因此我将 package 语句添加到每个模块。现在剩下的那些模块停止在职的。是什么赋予了?例子:
主应用程序.pl
#!/usr/bin/perl
use UtyDate;
my $rowDate = CurrentDate("YYYYMMDD");
UtyDate.pm
#!/usr/bin/perl
package UtyDate;
sub CurrentDate
{
#logic
}
return 1;
当我运行上面的代码时,我得到了错误
Undefined subroutine &main::CurrentDate called at...
.但是,如果我删除 package UtyDate;
来自 UtyDate.pm 的行,我没有收到任何错误。这种情况存在于我的几个但不是所有模块中。显然还有很多我没有展示的代码,但我很困惑我没有展示的任何代码如何影响我在这里展示的包/使用结构。
最佳答案
使用模块时,模块中的代码在编译时运行。然后在模块的包名上调用 import。所以,use Foo;
与 BEGIN { require Foo; Foo->import; }
相同
您的代码在没有 package
的情况下工作声明,因为所有代码都在包 main
下执行,由主应用程序代码使用。
当您添加 package
它停止工作的声明,因为您定义的子例程不再在 main
中定义, 但在 UtyDate
.
您可以使用完全限定名 UtyDate::CurrentDate();
访问子例程。或者当你 use
时将子例程导入当前 namespace 模块。
UtyDate.pm
package UtyDate;
use strict;
use warnings;
use Exporter 'import';
# Export these symbols by default. Should be empty!
our @EXPORT = ();
# List of symbols to export. Put whatever you want available here.
our @EXPORT_OK = qw( CurrentDate AnotherSub ThisOneToo );
sub CurrentDate {
return 'blah';
}
sub AnotherSub { return 'foo'; }
主程序:
#!/usr/bin/perl
use strict;
use warnings;
use UtyDate 'CurrentDate';
# CurrentDate is imported and usable.
print CurrentDate(), " CurrentDate worked\n";
# AnotherSub is not
eval { AnotherSub() } or print "AnotherSub didn't work: $@\n";
# But you can still access it by its fully qualified name
print UtyDate::AnotherSub(), " UtyDate::AnotherSub works though\n";
见 Exporter文档以获取更多信息。
关于Perl - 包/模块问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2977769/