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

In scriptA.plexistsuse DBI

In scriptB.plexistsrequire "scriptA.pl"

But we still cannot use the DBI package in scriptB.pl

Any way to handle this other than repeating use DBIin scriptB.pl?

+5
source share
3 answers

Scope useis a documented function:

use Module

Imports some semantics into the current package from a named module, usually by overlaying certain routines or variable names in your package.

You can do what you want, returning to the Stone Age, as in the following example, but please do not do this.

Using MyModuleas stand-in for DBI:

package MyModule;

use Exporter 'import';
our @EXPORT = qw/ foo /;
sub foo { print "$_[0]!\n" }

1;

and then call MyModule::foofromscriptA.pl

foo "from scriptA";

and scriptB.pl

foo "from scriptB";

#! /usr/bin/perl

use warnings;
use strict;

use MyModule;

do "scriptA.pl" or die;
do "scriptB.pl" or die;

print "done.\n";

:

from scriptA!
from scriptB!
done.

eval, , , .

, , scriptA scriptB - . , .

, Perl do require - . perlmod .

+8

, , , use DBI; , . .

+8

I wonder what exactly are you trying to achieve?

If you just want to reduce the template code (15 general declarations use Fooin each file), you can use a module, for example ToolKit, to create a standard set of modules to use:

Put this in Powerboy.pm:

 package Powerboy;

 use base 'ToolSet'; 

 ToolSet->use_pragma( 'strict' );
 ToolSet->use_pragma( 'warnings' );

 ToolSet->export(
     'DBI'  => undef,  # Export the default set of symbols
 );

 1; 

And then in your scripts just do:

 use Powerboy;

 # We have strict, warnings and DBI now.
+2
source

All Articles