Namespaces and require

R

Robert Billing

I have a fairly large suite of Perl scripts, and a configuration file
called db_config.pl which has some "configuration parameters" such as
where things are in the file tree, names of databases and tables and so
on. The intention is that this small file can be edited manually if needed.

When a stand-alone script is run it executes

require "db_config.pl" ;

which pulls in the definitions. This worked beautifully until I decided
that one new feature was best implemented as an object.

I therefore set up a package, let's call it dbadmin, which provides
methods to create an object, do something with it and finally output it
as HTML for display. This also works perfectly.

The problem is that if I require the configuration in main namespace it
is invisible in dbadmin and vice versa. If I put in two require
statements the clever behaviour of require means that only one does
anything.

At the moment I am getting at the definitions by writing things like
$Main::blivit, but is there a better, cleaner way of doing this?

Or in other works can I create a variable which is visible in all
namespaces?
 
A

A. Sinan Unur

5. If you think listing all those variable names is too much work
(I would :) ) you can move them into a hash and just export that:

package DBAdmin::Config;

use base qw/Exporter/;
our @EXPORT = qw/%Config/;

our %Config = (
blivit => "...",
...,
);

I would use a different name for the hash: Even %config is better, because
my mind automatically assumes %Config is the hash exported by Config:

perldoc Config

Sinan

--
A. Sinan Unur <[email protected]>
(remove .invalid and reverse each component for email address)

comp.lang.perl.misc guidelines on the WWW:
http://www.rehabitation.com/clpmisc/
 
R

Robert Billing

Ben said:
Quoth Robert Billing <[email protected]>:

No, you can't. You have several options here:

1. Refer to your config variables as $::blivit. It's a little
clunky, but not too long, and has the advantage of making them stand
out.

This is broadly what I have now.
2. Convert the config file into a real module, and 'use' it instead.
Then you can export variables with Exporter. Something like

package DBAdmin::Config;

I really like this one. It's so clean and tidy that I'll probably
convert everything to it in version two.

Thanks very much for your help.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top