Reputation: 48
In Perl if you try to lexically declare variable with my
after you declared a subroutine, this subroutine won't see this variable. However, subroutine declared after the variable will see the variable:
sub lol {
if (@arr) {
print "defined\n";
} else {
print "not defined\n";
}
}
my @arr = (1,2,3);
sub lol2 {
if (@arr) {
print "defined\n";
} else {
print "not defined\n";
}
}
lol; #prints "not defined"
lol2; #prints "defined"
However, if you set a variable without declaring it (@arr = (1,2,3);
) or declare variable with our
, both subroutines will see the variable.
Is it a bug or a feature?
Upvotes: 0
Views: 97
Reputation: 50657
All variables which are not defined with my
are implicitly our
(global/package) variables. So it is a feature. use strict;
pragma will force you to either use our
or my
explicitly in variable declaration.
To be more precise, quote from perldoc
strict vars
This generates a compile-time error if you access a variable that was neither explicitly declared (using any of my, our, state, or use vars ) nor fully qualified. (Because this is to avoid variable suicide problems and subtle dynamic scoping issues, a merely local variable isn't good enough.)
Upvotes: 1