Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

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 "subs.pl"; # 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 avail...how can I accomplish this?

Comment on use variable from main file in a 'require'd file?
Select or Download Code
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 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:

    t57:

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

    t57.pl:

    warn "\$CONFIG{key}: $CONFIG{key}\n"; 1;
Re: use variable from main file in a 'require'd file?
by ioannis (Priest) 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 'subs.pl', regardless if the file is loaded dynamically with require or compiled early with use.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (9)
As of 2014-09-22 10:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (188 votes), past polls