in reply to use strict and exporting package variables
After this assignment, $YourPackage::var and $MyPackage::var now access the same scalar variable. The left hand side is a glob. I've used a reference to a scalar on the right hand side; this makes an alias only for the scalar. If the right-hand-side were also a glob, all the types (array, hash, etc.) for the name 'var' would have been aliased.# export $MyPackage::var to $YourPackage::var *YourPackage::var = \$MyPackage::var;
This is how Exporter's import method works, except that it uses symbolic references to specify the names of the variables. For example:
This doesn't work for lexical variables, i.e. those declared with my, because they are not in the symbol table.$callpackage = 'YourPackage; $pkg = 'MyPackage'; $sym = 'var'; ${"${callpkg}::$sym"} = \${"${pkg}::$sym"};
However, it is possible to make an alias from the symbol table to a lexical variable:
So, you can write your own import method that exports lexical variables to the calling package, but you will have to either hard code the variable names or use eval, since the usual approach of symbolic references won't work.#!perl -l { my $var = 7; *Foo::var = \$var; print $Foo::var; foo(); print $var; } sub foo { # changes both $Foo::var and the lexical $var $Foo::var = 8; }
BTW, local does not declare a variable, as far as strict is concerned. In order to satisfy strict, variables without explicit package names must be declared with my or vars (or, in 5.6.0, our [offsite link]).
|
|---|