Perl模块用法

时间:2012-01-17 13:39:28

标签: perl perl-module

我正在尝试在/ usr / local / lib / perl

中创建自己的Perl模块

我设置了环境变量PERL5LIB:

$ env | grep PERL
PERL5LIB=/usr/local/lib/perl

如果我创建一个模块:$ PERL5LIB / My / ModuleTest.pm

$ ./test.pl 
Can't locate object method "new" via package "My::ModuleTest" (perhaps you forgot to load "My::ModuleTest"?) at ./test.pl line 8.

test.pl:

#!/usr/bin/perl

use strict;
use warnings;
use My::ModuleTest;

my $test = new My::ModuleTest;
print $test->check;

ModuleTest.pm:

package ModuleTest;

use strict;
use warnings;

sub new {
        my $class = shift;
        my ($opts)= @_;
        my $self = {};
        $self->{test} = "Hello World";

        return bless $self, $class;
}
sub check {
        my $self = shift;
        my ($opts) = @_;

        return $self->{test};
}
1;

我想使用$ PERL5LIB作为模块的库路径,将它们与安装目录隔离开来。

Perl @INC:

$ perl -le 'print foreach @INC'
/usr/local/lib/perl
/usr/lib/perl5/site_perl/5.8.8/i386-linux-thread-multi
/usr/lib/perl5/site_perl/5.8.8
/usr/lib/perl5/site_perl
/usr/lib/perl5/vendor_perl/5.8.8/i386-linux-thread-multi
/usr/lib/perl5/vendor_perl/5.8.8
/usr/lib/perl5/vendor_perl
/usr/lib/perl5/5.8.8/i386-linux-thread-multi
/usr/lib/perl5/5.8.8
.

2 个答案:

答案 0 :(得分:10)

在您的文件package My::ModuleTest;中尝试ModuleTest.pm - 您应该使用全名。

答案 1 :(得分:3)

更改模块的第一行
package ModuleTest;

package My::ModuleTest;