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

Aliasing symbol table entries does not work unless the aliasing assignment is executed by code in a different package. Why is this? BEGIN{ *main::mainvar = *someotherpkg::whatever } does not define $mainvar in package main if that assignment is executed in package main... or so it seems (see demo script below).

Can someone explain what is going on here? I've read 'perlmod' carefully and think I understand Perl symbol tables. But.

#!/usr/bin/env perl use strict; use warnings; use feature qw/say/; package Foo; our $foovar; BEGIN{ $foovar = 42 } package main; # This does not work (gets "Variable $mainvar is not imported") BEGIN{ package main; *main::mainvar = \$Foo::foovar; } # But this does work ... why? #BEGIN{ package xyzzx; *main::mainvar = \$Foo::foovar; } say $mainvar;

Replies are listed 'Best First'.
Re: Why don't *glob assignments affect the current pacakge?
by hv (Prior) on Aug 26, 2023 at 04:13 UTC

    It isn't that the glob assignment is not coming into effect, but that you have a true strict error when you use $mainvar without declaring it. The issue then is rather: why is accessing an undeclared variable not a strict error after a glob assignment in a different package? (Note that if you properly declare our $mainvar, no error is raised in either variant).

    I have a vague recollection that it is a long-standing deliberate exception - possibly a hack to help Exporter work, though I'm not confident of that. Certainly the behaviour goes back at least as far as perl-5.8.9, which is the oldest I have installed here; I suspect it was introduced sometime between 5.001m and 5.005.

      I have a vague recollection that it is a long-standing deliberate exception - possibly a hack to help Exporter work, though I'm not confident of that.

      The "documentation" I always refer to is tye's node here (and see my reply to that node).