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.
By default the
DBImodule imports nothing into the calling package so yes, in theory you could userequireinstead ofuse.But what are you hoping to gain from this? In this case
use DBIis equivalent toBEGIN { require DBI }, and if you omit theBEGINblock 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.
although dying may be a little extreme in your case.