in reply to 'use strict' and sharing globals between files

When run under "strict" variables have to be declared before they can be used (with the exception of some - or a rather a lot :-) built-ins like $_, @_ etc.

Now there are two types of variables in Perl: Package variables and lexical variables.

Lexial variables are declared with "my" and don't live in a namespace.

Package variables all live in a namespace and are declared either with "use vars" or with "our".

A namespace is introduced with a "package" declaration or it defaults to "main::" when there is no package-declaration.

In your case the second file uses strict and refers to a non-declared variable $name which is why it won't compile.

test1 declares the $name variable to be a package variable ("use vars") in the main-namespace (as there is no package-declaration).

Then test1 requires test2 (see perldoc -f require) which (as an approximation) loads, compiles and executes the 2nd script in the context where the require appears - i.e. in a context where we actually have a declared $name-variable (both files lack a package-declaration and so in both files unqualified (i.e. without explicit namespace) variables (like $name) belong to the "main"-namespace. This is why you can run test1.

Incidentally this only works with package-variables. If you change the "use vars qw($name)" to "my $name" both files fail as lexical variables cannot be seen in the required file.

hth

  • Comment on Re: 'use strict' and sharing globals between files

Replies are listed 'Best First'.
Re^2: 'use strict' and sharing globals between files
by Anonymous Monk on Apr 08, 2009 at 03:10 UTC
    Thanks to all three of you for your replies! I like to understand what's going on "under the hood" when I can, and now I'm a little closer. :)