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

Hi,
Is there a way to "automatically" import variables from an included file, to save the hassle of declaring each variable with "our $var" in the parent script? - other than not using strict :)
Cheers,
Reagen

Replies are listed 'Best First'.
Re: global vars
by borisz (Canon) on Jun 03, 2004 at 09:49 UTC
    use Exporter, see perldoc Exporter.
    Boris
Re: global vars
by davido (Cardinal) on Jun 03, 2004 at 16:00 UTC
    I like the method of reading in key/value pairs from a file to populate a hash. After all, even the package global symbol tables are just elaborate hashes.

    But if you really want to execute the variable declarations into existance you can use the Exporter module to help. See the documentation for that module, as well as our, and perlmod. This response has already been offered by others in this thread.

    I just wanted to add that you can use the fully qualified variable name even without Exporter.pm, and it won't break strictures. For example, if you have a variable in package "Variables", and the var is named "$hello", you could access it from package main like this: print $Variables::hello, "\n";

    Modules give namespace segregation, but you're still able to get at that namespace from the outside.


    Dave

Re: global vars
by mutated (Monk) on Jun 03, 2004 at 13:00 UTC
    You could always just put your key/value pairs into a file like this:
    KEY1=VALUE1 KEY2=VALUE2
    then slurp the values in at the beginning of your program:
    open(F,"conf.ini"); my %config = {}' while(<F>) { (my $key,$value) = split /=/; $config{"$key"} = $value; } close(F);
    If you want %config global just declair it as our instead of my, or pass it around with Exporter.


    daN.