can anyone explain to me why a variable that is declared in package can not be accessed by eval function unless it is used one time inside a sub?
(perl v5.16.3 MSWin32-x64-multi-thread ActiveState)
Package:
use strict;
use warnings;
package testPackage;
my $insertVar = "TEST";
sub testSub {
my $class = shift;
my $test = shift;
eval '$test="'.$test.'";';
return $test;
}
1;
Program:
use strict ;
use warnings ;
use testPackage ;
my $testVar = q[insertVar = ${insertVar}] ;
$testVar = testPackage->testSub( $testVar ) ;
print "$testVar\n" ;
Result when executing program:
Use of uninitialized value $insertVar in concatenation (.) or string at (eval 1) line 1. insertVar =
Now if I use the variable inside testSub (by e.g. printing it):
use strict;
use warnings;
package testPackage;
my $insertVar = "TEST";
sub testSub {
my $class = shift;
my $test = shift;
print $insertVar . "\n";
eval '$test="'.$test.'";';
return $test;
}
1;
Then the program runs exactly as I intended:
TEST
insertVar = TEST
myvariables declared in a file (outside of curlies) go out of scope when the file finishes executing (beforerequireandusereturn).$insertVarwill only continue to exist after the file has finished executing it if it's captured by a sub, and it will only be visible to the subs that capture it.For efficiency reasons, subs capture the fewest variables possible. If the sub doesn't reference
$insertVar, it won't capture it. Since your firsttestSubdoesn't reference$insertVar, it doesn't capture it. Since$insertVarhas gone out of scope by the time you calltestSub, it's not available toeval. You should get the warningVariable "$insertVar" is not available, but for reasons unknown to me, it's issued for the specific code you used.Your second
testSubreference$insertVar, sotestSubcaptures$insertVarand keeps it alive. Even though$insertVarhas gone out of scope by the time you calltestSub, it's available toevalsince it was captured by the sub.If you declare the variables using
our, they'll be global package variables, and thus won't go out of scope, and they'll be available toeval.