isevcik
isevcik

Reputation: 583

Why i can't access my variable declared in package from sub declared in the same package in Perl?

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;

Upvotes: 3

Views: 247

Answers (2)

tjd
tjd

Reputation: 4104

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.

Upvotes: 8

Michael Carman
Michael Carman

Reputation: 30831

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).

Upvotes: 4

Related Questions