bathpp
bathpp

Reputation: 470

Perl use module, keep getting Undefined subroutine &main error

I have a perl module DB.pm, inside is somthing like:

package GUI::DB;
use strict;
use DBI;
use vars qw(@ISA @EXPORT);
use Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(fun);
sub fun {
    my $dsn = "DBI:mysql:database=test";
    return $dsn;
}

Then I wrote test.pl:

#!/usr/bin/perl
use strict;
use warnings;
use lib '~/Downloads/GUI'; #Here is the path of the DB.pm module.
use DB;
my $aa = fun();

I have been trying to fix it for hours, I tried to use comment perl -l /path/to/file aa.pl and it gave me no error but the script didn't run at all, I am purely new to Perl, really stuck. Please help me.

EDIT: So the module's name is DB.pm and folder's name is GUI now, and I an using use DB in my script, still doesn't work, where should I save the DB.pm file?

Upvotes: 3

Views: 5777

Answers (2)

RobEarl
RobEarl

Reputation: 7912

Perl doesn't understand ~, see How do I find a user's home directory in Perl?

You also need to give use lib the directory which GUI/DB.pm is in and use GUI::DB:

use lib $ENV{HOME}."/Downloads";
use GUI::DB;

Upvotes: 3

ysth
ysth

Reputation: 98398

use HA; does a couple of things. First, it finds a file HA.pm in the perl library paths (@INC). Second, it calls HA::->import() to allow the HA module to do whatever initialization/exporting it wants; this relies on the module's package matching its filename. If it doesn't, this initialization is quietly skipped (method calls to an import method don't generate an error even if the method does not exist).

So explicitly call import on the package you want, or make the package name match the filename.

Upvotes: 4

Related Questions