So I don't know if this belongs in SoPW or Meditations, but I stumbled across the following (what I would call) inconsistency, and wondered if anybody had an explanation...
This does not work:
use strict 'vars';
BEGIN { *main::foo = \@main::foo }
print "Foo: (@foo)\n";
__OUTPUT__
Variable "@foo" is not imported at foo.pl line 10.
Global symbol "@foo" requires explicit package name at foo.pl line
+10.
foo.pl had compilation errors.
But this works fine:
use strict 'vars';
package somePkg;
BEGIN { *main::foo = \@main::foo }
package main;
print "Foo: (@foo)\n";
Somewhat interestingly, this seems to work okay, too:
use strict 'vars';
# We're already in package main
BEGIN { *pkg::foo = \@pkg::foo }
package pkg;
print "Foo: (@foo)\n";
And this fails, as well:
use strict 'vars';
package pkg;
BEGIN { *pkg::foo = \@pkg::foo }
print "Foo: (@foo)\n";
I noticed that running "
perl -MO=Deparse" on the last snippet, above, shows the symbol table manipulation being (*cough*) "optimized" (*cough*) thusly:
package pkg;
sub BEGIN {
*foo = \@foo;
}
Perhaps that's why "strict" doesn't allow me to access the unqualified "@foo" directly? Because -- since it's not in a different package -- something, somewhere, isn't creating the corresponding lexical alias? *Shrug*
Finally, this is mostly the same as number 2, above, which also works, but in the fewest lines:
use strict 'vars';
BEGIN { package pkg; *main::foo = \@main::foo }
print "Foo: (@foo)\n";
__OUTPUT__
Foo: ()
PS - Before you say "Just use 'our'" ...
Yes, I know. There's More Than One Way To Do It, and I'm MORE curious about the underlying question of why THIS way happens to fail.
Thanks! :-D
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.