OneTrueDabe has asked for the wisdom of the Perl Monks concerning the following question:
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:But this works fine: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.
Somewhat interestingly, this seems to work okay, too:use strict 'vars'; package somePkg; BEGIN { *main::foo = \@main::foo } package main; print "Foo: (@foo)\n";
And this fails, as well:use strict 'vars'; # We're already in package main BEGIN { *pkg::foo = \@pkg::foo } package pkg; 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:use strict 'vars'; package pkg; BEGIN { *pkg::foo = \@pkg::foo } print "Foo: (@foo)\n";
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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Creating "Lexical" Symbol Table Aliases (a la "use vars") From The Same Package
by tobyink (Canon) on May 08, 2014 at 17:34 UTC | |
Re: Creating "Lexical" Symbol Table Aliases (a la "use vars") From The Same Package
by moritz (Cardinal) on May 09, 2014 at 08:42 UTC | |
Re: Creating "Lexical" Symbol Table Aliases (a la "use vars") From The Same Package
by LanX (Saint) on May 08, 2014 at 19:59 UTC | |
Re: Creating "Lexical" Symbol Table Aliases (a la "use vars") From The Same Package
by Anonymous Monk on May 09, 2014 at 00:38 UTC | |
by tobyink (Canon) on May 09, 2014 at 10:50 UTC | |
by Anonymous Monk on May 09, 2014 at 11:29 UTC | |
Re: Creating "Lexical" Symbol Table Aliases (a la "use vars") From The Same Package
by karlgoethebier (Abbot) on May 08, 2014 at 17:38 UTC |