Reputation: 54373
I have a large script that has no database connection yet. I need one for a tiny new feature. Is it safe to add a naked block to require DBI
where I need it or do I need to import something?
# Lots of no-database code here...
my $obj;
{
require DBI;
my $dbh = DBI->connect('dsn');
$obj = ModuleThatNeedsDBH->new(dbh => $dbh);
}
$obj->fancyStuff();
# More no-database code...
The block is to keep $dbh
hidden from the rest of the program of course.
Upvotes: 2
Views: 349
Reputation: 132858
Although by default DBI imports nothing, that doesn't mean that it doesn't do any internal processing or setup when you use it. Unless a module's documentation says otherwise, you should use the full process to ensure that everything that should happen actually does. You might want to see How can I dynamically include Perl modules without using eval?.
Also, I'd consider making ModuleThatNeedsDBH
automatically making one if it doesn't get on in its argument list. Dependency injection is nice, but that doesn't mean you are required to force the higher level to create the things that you need.
Upvotes: 2
Reputation: 126742
By default the DBI
module imports nothing into the calling package so yes, in theory you could use require
instead of use
.
But what are you hoping to gain from this? In this case use DBI
is equivalent to BEGIN { require DBI }
, and if you omit the BEGIN
block you will be imposing the lengthy process of loading the package during run time which is undesirable.
Note that you must also handle any failure to connect to the database.
my $dbh = DBI->connect('dsn', 'user', 'pass')
or die $DBI::errstr;
although dying may be a little extreme in your case.
Upvotes: 3