Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`use` package scope: how to make it cross files?

Tags:

perl

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?

like image 379
powerboy Avatar asked Aug 15 '10 01:08

powerboy


2 Answers

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.

like image 190
Greg Bacon Avatar answered Nov 16 '22 03:11

Greg Bacon


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.

like image 44
Ether Avatar answered Nov 16 '22 02:11

Ether