sairanga talari
sairanga talari

Reputation: 57

How to use one module in another module in perl?

Iam writing a perl script ,in which iam using a module utils.pm and in utils.pm iam using another module DB.pm in which i have a sub routine connetToDB().

in utils.pm iam writing

use DB qw (connectToDB());

and below iam calling that subroutine as

my $connection=DB::connectToDB();         (This is line 30)

it is giving an error like follows. Can someone pls help?

Undefined subroutine &DB::connectToDB called at utils.pm line 30.

you can see the DB.pm code here

Upvotes: 0

Views: 689

Answers (2)

zdim
zdim

Reputation: 66873

The direct error in the shown code is that inside qw() you need names. The use pragma

Imports some semantics into the current package from the named module

(my emphasis). The "connectToDB()", with parentheses, is not the correct name for the subroutine. The error message simply says that it didn't find such a sub.

So just drop the parens, use DB qw(connectToDB);.


The code for the package was added to the question and here are some comments.

A similar fix is needed with your @EXPORT: you need the subroutine names (lose &).

Perhaps more importantly, you defined the sub using prototypes. Your sub is consistent with the prototype you use so I'll assume that it's done on purpose.

This is a very advanced (mis?)feature, which is very different from similar looking devices in other languages and is normally not needed. Chances are that you expect wrong things from prototypes. Go search for it. I'd advise against.

A side note: the prototype-related () and & are not a part of the subroutine name.

The last executed statement that returns in a module must return true, or code won't compile. The convention to ensure this is to put 1; at the end of the package.

Finally, you shouldn't name the module DB as that namespace is used internally by Perl. Also, such a generic name is just not good for a module -- it makes it easy to run into conflicts.

Upvotes: 4

Hema Mahadev
Hema Mahadev

Reputation: 1

use DB qw(connectToDB);

my $connection=DB->connectToDB();

or

if you have defined a constructor "new" in DB.pm module then

my $connection=DB->new();

my $result = $connection->connectToDB();

Upvotes: 0

Related Questions