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

Hello, I am using Solaris 2.8 and Perl 5.005_02 on a SPARC. I attempted to use "use" or "do" to load a PERL parsable configuration file. However, when I declare the variable in the main program with "my" a call to either "do" or "require" of the configuration file causes PERL to think it is a different program scope. Interestingly enough, if I use "local" (which supposedly hides global variables temporarily) it works fine (?!) I have no problem with using "local" except "local" will not work with "strict" since it is only a local decl not global. I'd rather not repeat "local" for every "my", which defeats the purpose of a simple program. Is there a simple answer of how to make a one line configuration file load and still have "strict" active? Thanks, Daniel
  • Comment on Configuration files via require or do and my, local.

Replies are listed 'Best First'.
Re: Configuration files via require or do and my, local. (global/package-scoped)
by ybiC (Prior) on Mar 24, 2002 at 17:36 UTC
    One way to address this problem is to declare the config file variables as package-scoped in the main program (before reading the config file):

    use vars qw($scalar1 @array2 %hash3);

    Then they're available in all blocks of the main program, including the external config file, without 'my' or 'local'.   There can be significant drawbacks associated with global vars, but this approach works in Perl back to at least 5.04.   Whereas 'our' was new in 5.6, I think.

    You might find Dominus' Coping with Scoping to be a relevent read.

        cheers,
        Don
        striving toward Perl Adept
        (it's pronounced "why-bick")
Re: Configuration files via require or do and my, local.
by ehdonhon (Curate) on Mar 24, 2002 at 17:28 UTC

    When you use my in the file being required, you are declaring the variables within the file scope. When you leave the file, they are no longer accessable. I would recommend using 'our' instead of 'my'.

      I found the answer: "my" is space scoped (context NOT carried outside the file) "local" is run-time scoped (context into other files beneath this scope.) However, you can use "vars" in conjunction with "use strict" to decl global vars. Make sure to go back and remove the "my" in front of the variables. Thanks, Daniel

        This:

        use vars qw( $foo ); $foo = 1;

        And this:

        our $foo = 1;

        Do the exact same thing. Though, "our" may not be available to you in Perl 5.005.

Re: Configuration files via require or do and my, local.
by braughing (Sexton) on Mar 24, 2002 at 17:29 UTC
    There are some answers at this thread. (Mine's wrong though.)