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

Hi,
I am trying to understand global variables.
I think I have a reasonable understanding of them in a single script (with or without subs), but my understanding wanes a bit with included files.
I was under the impression that the following would work, but it doesnt. Anyone tell me why?
#!/usr/bin/perl use strict; use warnings; require "inc.conf"; our $var; print $var , "\n"; exit;
And the contents of inc.conf...
#!/usr/bin/perl use strict; use warnings; my $var = "blah"; 1;
Cheers,
Reagen

Replies are listed 'Best First'.
Re: global variables
by Fletch (Bishop) on May 31, 2004 at 14:09 UTC

    The my in "inc.conf" declares $var as lexically scoped (in this case the body of the file "inc.conf"). As soon as perl is done running the code in "inc.conf", that $var goes away. It has no relation to $main::var which is what your our $var; has made available without an explicit package name. See also MJD's Coping with Scoping.

Re: global variables
by davidj (Priest) on May 31, 2004 at 14:12 UTC
    This is from the Llama book:

    "a require happens at run time, so it occurs too late to serve as a declaration in the file invoking the require."

    If you want the variables in inc.conf to be available globally in your program you will need to "use inc.conf" instead of "require inc.conf". The reason for this is that "use" is done at compile time.

    hope this helps,
    davidj

    update:please disregard this post. I misunderstood the question, so my reply is incorrect. And please do not flog to too badly :)

    davidj
      So the code can just be:
      use 'inc.conf';
      ?? Or do i need to include a use lib, because the above isnt working for me.
      I get the error:
      syntax error at global_vars.pl line 5, near "use 'inc.conf'"

      Cheers,
      Reagen

        no, it will work allright if you just change the   my $var = "blah";   to   our $var = "blah";   in   inc.conf.

        Cheers, Sören