Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

use variable from main file in a 'require'd file?

by Anonymous Monk
on Jun 12, 2006 at 16:29 UTC ( #554851=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

i'm using a hash in my main script to store some configuration info:
#!/usr/bin/perl -w use strict; require ""; # declare and define config my %CONFIG = ('key' => 'value');
and in a library file, i store some subroutines that use this config hash:
sub test { print $CONFIG{'key'}; } 1;
this, of course, doesnt work. the test() sub doesnt see the %CONFIG hash, because its declared local with my() in a whole other file. i've tried declaring the hash with our(), to no can I accomplish this?

Replies are listed 'Best First'.
Re: use variable from main file in a 'require'd file?
by sgifford (Prior) on Jun 12, 2006 at 16:46 UTC
    If I declare %CONFIG with our and put the declaration and setting before the require, this works fine for me. I have this:


    #!/usr/bin/perl -w use strict; our %CONFIG = (key => 'value'); require '';

    warn "\$CONFIG{key}: $CONFIG{key}\n"; 1;
Re: use variable from main file in a 'require'd file?
by Fletch (Chancellor) on Jun 12, 2006 at 16:41 UTC

    You probably didn't try hard enough. If you declare (in your main program):

    our %CONFIG = ( ... );

    Then anything else can access it via %main::CONFIG (or %::CONFIG). If it's declared in a different package you'd of course use that package name rather than main. See also Exporter.

    Update: Oooh, good catch; I didn't notice the relative ordering of the require and the declaration. You'd need to either swap it or wrap the declaration in a BEGIN block to ensure it happened as soon as possible as well.

Re: use variable from main file in a 'require'd file?
by ioannis (Abbot) on Jun 12, 2006 at 18:06 UTC
    There are more solutions. But let's remember the root of our troubles: the scope of the my operator does not extend to other files; it is not (directly) visible by '', regardless if the file is loaded dynamically with require or compiled early with use.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://554851]
Approved by philcrow
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2020-07-04 06:40 GMT
Find Nodes?
    Voting Booth?

    No recent polls found