Perl - 包/模块问题

bry*_*esk 7 perl perl-module

从我读过的关于使用Perl模块的所有内容来看,基本用法是:

  • .pm扩展名的模块文件,其中包含语句package <name>,其中<name>是没有扩展名的模块的文件名.
  • 使用模块的代码文件包含该语句use <name>;.

我正在编码的应用程序有一个主代码脚本,它使用大约5个模块.我忘记package <name>在模块中包含该语句,但我的代码仍然可以正常运行该use <name>语句.我开始收到Undefined subroutine其中一个模块的错误,所以我将package语句添加到每个模块中.现在其余的模块停止工作了.是什么赋予了?

例:

mainapp.pl

#!/usr/bin/perl
use UtyDate;
my $rowDate = CurrentDate("YYYYMMDD");
Run Code Online (Sandbox Code Playgroud)

UtyDate.pm

#!/usr/bin/perl
package UtyDate;
sub CurrentDate
{
    #logic
}
return 1;
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,我收到错误Undefined subroutine &main::CurrentDate called at....但是,如果我package UtyDate;从UtyDate.pm中删除该行,我没有错误.这种情况存在于几个但不是所有模块中.

显然有很多代码我没有展示,但我很困惑,我没有展示的任何代码可能会影响我在这里展示的包/使用结构.

dao*_*oad 10

使用模块时,模块中的代码在编译时运行.然后在模块的包名称上调用import.所以,use Foo;是一样的BEGIN { require Foo; Foo->import; }

您的代码在没有package声明的情况下工作,因为所有代码都是main在主应用程序代码使用的包下执行的.

添加package声明时它停止工作,因为您定义的子程序不再被定义main,而是在UtyDate.

您可以使用完全限定名称访问子例程,也可以在模块UtyDate::CurrentDate();时将子例程导入当前名称空间use.

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'; }
Run Code Online (Sandbox Code Playgroud)

主程序:

#!/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";
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅导出器文档.

  • OP应该首先阅读`perlmod`(http://search.cpan.org/perldoc/perlmod)作为理解`Exporter`中发生的事情的先决条件. (2认同)