http://qs321.pair.com?node_id=1214559


in reply to Importing a variable into a package

The trick is that *T::y = \"b"; needs to happen at compile time. Try adding a BEGIN to your first block and your code works. Remember that use Module LIST; is equivalent to BEGIN { require Module; Module->import( LIST ); }.

Update: I'm not completely sure how you're connecting this question to Re: Text::Template and delayed use vars - could you make that clearer? Without digging into the Text::Template source code, I suspect that something slightly different is going on there. First, note that fully qualified variable names ($T::x) are exempt from strict vars.

Second, the above statement can be generalized to: Perl needs to know about the variable name before compiling a piece of code. That's why in your example, you need to move the "predeclaration" of $T::y to the compile time before the runtime of the main script by placing it in a BEGIN block (note you could also use the vars pragma, which just hides the same thing behind a nicer syntax).

But if during the runtime of your main script, you compile and run another piece of code via require, do, or eval, then that code's compile time is later, during the runtime of your script (confused yet? ;-) see BEGIN, UNITCHECK, CHECK, INIT and END). That means the following:

use warnings; use strict; eval ' package T; print "A: $x\n"; 1 ' or warn "A: $@"; # => Global symbol "$x" requires explicit package name { no warnings 'once'; *T::x = \"foo"; } # runtime of main! eval ' package T; print "B: $x\n"; 1 ' or warn "B: $@"; # => now works