Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Module usage

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
.
like image 567
Mose Avatar asked Jan 17 '12 13:01

Mose


People also ask

What is the use of Perl modules?

A module in Perl is a collection of related subroutines and variables that perform a set of programming tasks. Perl Modules are reusable. Various Perl modules are available on the Comprehensive Perl Archive Network (CPAN).

How do I write a Perl module?

In this case, you need to create a new file named FileLogger.pm . pm stands for Perl module. Third, make the FileLogger module a package by using the syntax: package FileLogger; at the top of the FileLogger.pm file. Fourth, write the code for subroutines and variables, and put the code into the FileLogger.pm file.

How do I run a package in Perl?

A Perl package is a collection of code which resides in its own namespace. Perl module is a package defined in a file having the same name as that of the package and having extension . pm. Two different modules may contain a variable or a function of the same name.


2 Answers

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

like image 154
Konerak Avatar answered Sep 25 '22 14:09

Konerak


Change the first line of your module from

package ModuleTest;

to

package My::ModuleTest;
like image 22
mat Avatar answered Sep 25 '22 14:09

mat