How can an external injected global variable be accessed simply by its name?
That snippet does not work without fully qualifying the variable:
#! /bin/perl
use strict; use warnings;
package Haus;
sub test{
print __PACKAGE__."\n";
# Works
print "qualified var [$Haus::var]\n"; # OK
# not working, why and how to achieve that without
# local "our $var" instead external injected
print "simple var [$var]\n"; # NOK
}
package main;
$Haus::var=1;
Haus::test();
CodePudding user response:
You (appropriately) asked Perl to not let you use $var
without first declaring $var
.
strict vars
This generates a compile-time error if you access a variable that was neither explicitly declared (using any of
my
,our
,state
, oruse vars
) nor fully qualified. (Because this is to avoid variable suicide problems and subtle dynamic scoping issues, a merelylocal
variable isn't good enough.) See "my" in perlfunc, "our" in perlfunc, "state" in perlfunc, "local" in perlfunc, and vars.
All you need to do is declare $var
. Both our $var;
and use vars qw( $var );
would do the trick here.
You could also remove the request (by using use strict; no strict qw( vars );
), but there's no reason to do that, and plenty not to.
CodePudding user response:
I think, that you got a compile time error because stricture is enabled and $var
is not declared in your example. Declare the variable with our
so that Perl knows that you mean $Haus::var
. See our