Possible Duplicate:
error of importing DBI in Perl
I have a problem when I use the DBI module in another module, script.pm.
package CC;
use DBI;
use strict;
use Alias;
my $dbFile = 'XXXXXXXX.db';
my $db = DBI->connect("dbi:SQLite:$dbFile","","",
{RaiseError =>1, AutoCommit => 1})or "Unable to connect: $DBI::errstr\n";
use Alias qw(attr);
our ($CURRENTOFFSET,@LANGUAGE);
sub new {
my $that = shift;
my $class = ref($that)|| $that;
my $self = {
CURRENTOFFSET=> undef,
LANGUAGE => []
};
bless($self, $class);
return $self;
}
Substantive
Conventionally, a package
XYZis kept in a fileXYZ.pm; Perl won’t find your package otherwise. Thus, your file should beCC.pmrather thanscript.pm.Note that a package
Organization::Team::Purposeis kept in a filePurpose.pm, but the file is kept in a sub-directoryOrganization/Teamand the base directory holdingOrganizationhas to be found by Perl (using-I/some/whereifOrganizationis a sub-directory of the directory/some/where, for example; if it is a sub-directory of the current directory, it will be found anyway).You should probably review the
orclause after your connection attempt. Normally, you do adieorcroakthere. You simply evaluate a string, which is not very useful.You have:
You should consider what to do, but one technique is:
The downside of that is that this is going into a module, and it isn’t necessarily a good idea to croak in the BEGIN code of a module (and I’m making an assumption that the code is executed as the module is loaded). You might need to store the
undefdatabase handle and protect other methods from using it. You might be better off deferring the ‘connect to database’ operation until the constructornewis used (possibly for the first time). It is at least legitimate to raise errors at that point.As the answer by DVK noted (before I wrote my answer), modules should end with
1;to indicate successful loading. Maybe you can exploit that to report an error on failure to load – the final condition might be ‘defined $db ? 0 : 1;‘ (or even just ‘defined $db;‘), but it would be crucial to generate an error message somehow to explain the problem.Trivia
You should be ruthlessly consistent in the spacing around operators, too. Your example includes:
which would be better written as:
The first might benefit from a little more space:
It doesn’t directly affect the operation of the code. It does make it a little less easy to read. Learning to be consistent is an important part of learning to program.