In scriptA.pl
, there is use DBI
In scriptB.pl
, there is require "scriptA.pl"
But we still cannot use DBI package in scriptB.pl
Any way to handle this except repeating use DBI
in scriptB.pl
?
The scoped nature of use
is a documented feature:
use Module
Imports some semantics into the current package from the named module, generally by aliasing certain subroutine or variable names into your package.
You could do what you want by going back to the stone age as in the following example, but please don't.
Using MyModule
as a stand-in for DBI
:
package MyModule;
use Exporter 'import';
our @EXPORT = qw/ foo /;
sub foo { print "$_[0]!\n" }
1;
and then calling MyModule::foo
from scriptA.pl
foo "from scriptA";
and from scriptB.pl
foo "from scriptB";
all kicked off from a main program of
#! /usr/bin/perl
use warnings;
use strict;
use MyModule;
do "scriptA.pl" or die;
do "scriptB.pl" or die;
print "done.\n";
gives the following output:
from scriptA! from scriptB! done.
You also could disable the scoping safety-feature with nasty eval
games, but please don't do that either.
If your design needs improvement—maybe scriptA
and scriptB
belong in the same package—that would be a far better investment of your time. Otherwise, bite the bullet and expend nine keystrokes.
Please note that executing Perl libraries at runtime via do
or require
are a seriously dated approaches. The perlmod documentation describes the modern approach.
There are ways, but they are all more ugly, hacky and unclean than simply typing use DBI;
in every file that uses it. This is the best practice and is quite normal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With