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

I'm not understanding something about namespaces when using "require". For example
#this filename is test.pl use strict ; use warnings ; my $a ; require "set_a.pl" print "a is $a\n" ;
And
#this filename is set_a.pl $a=1 ;
When I run test.pl, $a is not initialized. I thought "set_a.pl" would run in the "main" namespace, so the line "$a=1" in set_a.pl would be initializing the variable $a in the main namespace. What did I forget about namespaces, or never learn? :-)

Replies are listed 'Best First'.
Re: namespaces and variable initilization with require 'file'
by JavaFan (Canon) on Oct 01, 2008 at 15:11 UTC
    You are quite right; in set_a.pl the variable is initialized in the main name space. However, in test.pl, you have 'my $a', so when you print $a, you are referring to the lexical $a, not the package variable $main::a (which you initialize in set_a.pl). Lexicals and package variable are quite distinct.

    And I hope you are using '$a' just for this example - $main::a is special for 'sort'.

      Thanks, that was it. Remembering the nuance of lexicals are too often my nemesis. And yes, the $a was just for the example.
Re: namespaces and variable initilization with require 'file'
by broomduster (Priest) on Oct 01, 2008 at 15:46 UTC
    As an alternative to $main::a (noted by JavaFan), you can declare using our.
Re: namespaces and variable initilization with require 'file'
by ikegami (Patriarch) on Oct 01, 2008 at 19:05 UTC

    require is for modules (files with a package directive).
    do is for modulesscripts (files without a package directive).

    It might even fix your problem without further change, but I'm not sure.

      Did you really mean to use the word 'modules' for both kinds of files? I guess in any case that you didn't mean that require can only be used on files with a package directive, because that's certainly not true:
      $ echo 'print "Included a.pm\n";' > a.pm $ perl -e 'require a' # Included a.pm
      works just fine for me. I understood a big difference (though by no means the only one) to be between whether you want to allow the file to be read multiple times, in the sense that
      $ perl -e 'require a; require a' # Included a.pm $ perl -e 'do "a.pm"; do "a.pm"' # Included a.pm\ # Included a.pm
      do different things.

        The repeated use of "modules" was a copy and paste error.

        And right, I wasn't talking about the abilities of the respective commands, but their purpose. do executes a file. So does require. The difference is that require will only execute a file once per run, so it only makes sense to use require for files that load a module.