I don't understand why can't access variable $var in sub mysub. Both packages are defined in the same file exactly as in this example:
use warnings;
use strict;
Util::mysub();
package Util;
use warnings;
use strict;
my $var = 'i have a value!';
# prints 'var in package: i have a value!'
print "var in package: $var\n";
sub mysub {
# generates warning 'Use of uninitialized value $var...'
print "var in sub: $var\n";
}
1;
You call Util::mysub() several lines prior to assigning to the file scoped $var.
If your package were in a seperate file, the use statement and its implied BEGIN block would give the assignment priority. Alternatively, you could put the package definition first or use your own BEGIN block.
You can access the variable inside your sub, it just hasn't been set yet.
my has both compile-time and run-time behavior. At compile-time it declares a variable name for the remainder of the enclosing scope, thus making use strict happy. Initialization happens at run-time when control flow reaches the declaration. Because your call to mysub() happens before control flow reaches the my $var = ..., the value of $var seen in mysub is undef and perl emits a "Use of uninitialized value..." warning. If you called your sub after the my $var = ... it would be defined and you'd see that value instead (and no warning).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With