9

I am trying to create my own Perl module in /usr/local/lib/perl

I have the environmental variable PERL5LIB set:

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

If I create a module: $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;

I want to use the $PERL5LIB as the library path for my modules to segregate them from the installation directory.

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
.
xxfelixxx
  • 6,512
  • 3
  • 31
  • 38
Mose
  • 541
  • 1
  • 11
  • 27

2 Answers2

10

Try package My::ModuleTest; in your file ModuleTest.pm - you should use the full name.

Konerak
  • 39,272
  • 12
  • 98
  • 118
  • 2
    Thanks. Great question btw - all the necessary info was there, you've showed everything you tried, allowed us to recreate the situation, perfectly formatted... you deserve fast answers :] – Konerak Jan 17 '12 at 14:20
  • One last question, is it necessary for root to have the PERL5LIB env variable or will it look to /usr/local/lib/perl as part of its path? – Mose Jan 17 '12 at 23:57
  • @user196096: great question - that's why [someone else on stackoverflow already asked it (link)](http://stackoverflow.com/questions/2526804/how-is-perls-inc-constructed-aka-what-are-all-the-ways-of-affecting-where-pe), and it was answered too! :] – Konerak Jan 18 '12 at 09:41
3

Change the first line of your module from

package ModuleTest;

to

package My::ModuleTest;
mat
  • 1,645
  • 15
  • 36