Re: Global scope

[email protected] ("Vance E. Neff") Thu, 23 Apr 2009 14:18:31 -0400
Newsgroups perl.beginners.cgi
Organization Vance's Consulting Co.
Message-ID <[email protected]>
Gunnar,

Thanks for your response!

That is what I started with but then I was getting the error:
xxx.pm: "our" variable $DataBaseType redeclared at xxx.pm line nn.

Well it turns out that error was caused by some other problem.  I did
not realize that "our" was not a function.  So you can't do something
like this:
our $variable = "value1" if (something is true);
our $variable = "value2" if (something else is true);

I fixed that and things seem to working as expected.

Thanks a lot!

Vance



Gunnar Hjalmarsson wrote:
> Vance E. Neff wrote:
>>  I have a module options.pm defined as:
>> <pre>
>> package options;
>> use strict;
>> use base qw(Exporter);
>> our @EXPORT = qw(@BenefitsOptions %BenefitsOptions);
>> our @EXPORT_OK = qw();
>>
>> our %BenefitsOptions =    (
>>     "Dental"    =>    1,
>>     "Full"        =>    2,
>>     "Base"        =>    3,
>>     "Comm."        =>    4,
>>     "END"
>>     );
>> @BenefitsOptions = ();
>>
>> 1;
>> </pre>
>>
>> and at the beginning of each of my CGI programs I have the line:
>> use options;
>>
>> each program may access the variables defined in options.pm and may 
>> call other .pm modules that also need to have access to those same 
>> options.pm variables and those .pm modules might call another.pm 
>> modules that need to access those same variables defined in options.pm.
>>
>> I read the perlmod, perlobj, Exporter, perltoot and frankly, I'm now 
>> more confused then ever.
>> I tried putting the variable declarations in a BEGIN block with no 
>> success.
>>
>> I'm getting the error:
>> Global symbol "xx" requires explicit package name at module.pm line nn.
> 
> I for one get: "Global symbol "@BenefitsOptions" requires explicit 
> package name at options.pm line 14."
> 
> Besides that, you need to realize that when you say
> 
>     use options;
> 
> in your script, you import the symbols into the package where that 
> statement is placed, probably package main. The variables are indeed 
> available also in other packages, but you need to either say
> 
>     use options;
> 
> in each of those modules as well, or use the fully qualified name, e.g.
> 
>     %options::BenefitsOptions
> 
>> What is the best way to do this?
> 
> One way is to make use of the %ENV hash.
> 
>     $ENV{BenefitsOptions} = {
>         Dental  => 1,
>         Full    => 2,
>         Base    => 3,
>         'Comm.' => 4,
>     };
> 
> Then you can say anywhere in your program:
> 
>     foreach ( keys %{ $ENV{BenefitsOptions} } ) {
>         print "$_ = $ENV{BenefitsOptions}->{$_}\n";
>     }
>