Hi,
Background:
I have a script which refers to a bunch of variables holding parameter values. These parameters have sensible default values, which I would like to assign in a loop at the start, but I also want to allow the user to alter them using command-line arguments. Obviously I could just use a hash and be done with it, but I thought I'd be clever and set things up so I could refer to the variables directly by name (e.g. $K, $SLIDE, $MAXMEM instead of $v{K}, $v{SLIDE}, $v{MAXMEM} etc.), for brevity. Finally, as is now my custom, I wanted everthing to be
strict- and warnings-clean.
So, I thought I would just set up a hash containing the names and default values of the variables, and run
eval "our \$$name = \$val"; inside a loop in a BEGIN block, to assign defaults for each. This didn't work; I eventually realised that the effect of the
our modifier only lasts for lexical scope, so when the eval() exits, the variable needs full package qualification again. Even if I wasn't using eval(), lexical scope would still end at the end of the BEGIN block, so I'm satisfied that there's no way to use
our to make the variables visible to the main body of the code. (That is, without listing all the names again outside the BEGIN block, which defeats most of the purpose.)
I was able to get the thing running using the "obsolete"
use vars, which has no lexical scope restriction. I replaced my eval() expression with
eval "use vars '\$$name'; \$$name = \$val"; and everything worked. But I was a bit worried about the "obsoleteness" of
use vars, so I had a look inside the vars.pm module to see if I could understand what it was doing and then hand-craft a solution myself. And basically, the lines that does the work in vars.pm look like:
$sym = "${callpack}::$sym" unless $sym =~ /::/;
*$sym =
( $ch eq "\$" ? \$$sym
: $ch eq "\@" ? \@$sym
: $ch eq "\%" ? \%$sym
: $ch eq "\*" ? \*$sym
: $ch eq "\&" ? \&$sym
: do {
require Carp;
Carp::croak("'$_' is not a valid variable name");
});
I tried many variations of the typeglob-assignment code in vars.pm and couldn't get anything to work, before discovering that apparently it is critical that the assignment take place
in a different package.
So now at last we come to the question: Why does this code:
perl -Mstrict -Wle 'BEGIN { *main::x = \$main::x; } $x = 42;'
fail with
Variable "$x" is not imported at -e line 1.
Global symbol "$x" requires explicit package name at -e line 1.
Execution of -e aborted due to compilation errors.
while
perl -Mstrict -Wle 'BEGIN { package ARBITRARY_PACKAGE_NAME; *main::x =
+ \$main::x; } $x = 42;'
runs happily? Why do you need to be in a different package to persuade Perl to let you refer to a global variable without a package qualifier?
Thanks in advance,
JRH