Short version
Is it possible to access variables from a module declared as our using unqualified names within the BEGIN code block, but using qualified names outside? In particular, can this be done without explicitely naming the package in the module file?
Example
Let demomod.pm be
use strict;
use warnings;
package demomod;
our $foo;
BEGIN { $foo = 42; }
1;
and demoscript.pl be
#!/usr/bin/perl -Tw
use strict;
use warnings;
BEGIN { @INC = ('.', @INC); }
use demomod;
print $demomod::foo."\n";
In this case, all names agree, and everything works as it should. Is there a way to omit the line package demomod; from the demomod.pm code and still let this work?
Motivation
The reason why I’m asking is because I encountered something along these lines during a recent upgrade of Foswiki. That software has a module Foswiki.pm which does not have a (EDIT: seems the package linepackage line only got lost in my local copy, for reasons unknown). It declares and initializes a variable $engine like in my example. There also is a CGI script called view which sets @INC and then does use Foswiki (); followed by $Foswiki::engine->run(). This last line always fails for me due to the variable not being initialized:
Can't call method "run" on an undefined value at …/view
In the BEGIN block of the module, $engine is set correctly but $Foswiki::engine apparently is not. So it looks like there were two variables here, one qualified and a different one unqualified.
All that code apparently works for others, and a previous version used to work for me as well, without a . So while I try to understand how this broke, I also try to understand how this could work before, without that line in place. Is there some mechanism that would make this work?package line either
If you have no
packagestatement in your code then any package variables will be declared into themainpackage. So no, you cannot do what you describe.If you look at line 2 of the
Foswikicode that you linked, you will see that it does have a package statement.