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


In reply to Re: 'use strict' and sharing globals between files by morgon
in thread 'use strict' and sharing globals between files by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.