in reply to Scope, package, and 'my' variables
Since it seems (when i started this at least) that nobody else has explained what the "lexical" part of "lexical scoping" means I might as well give it a go: the term "lexical" is used because the scoping is based on the lexical context of the declaration of the var. Lexical: "Of or relating to the vocabulary, words, or morphemes of a language." So this means that scope of a lexical is the smallest enclosing block in the file the declaration occurs within. OTOH, package statements have NO EFFECT on lexical variables. Perl doesn't care at all about packages and namespaces when dealing with lexicals. Consider:
#!perl -l my $foo='$foo'; package Bar; print $foo; #prints '$foo' package Baz; print $foo; #prints '$foo'
Perl has a different type of variable that are called variously "dynamically scoped" or "globals" or "package variables" or the like. These variables are NOT scoped lexically. (In fact its arguable they arent scoped at all, depending on your definition of scoped.). Traditionally when not using strict any variables mentioned are assumed to be package variables. When using strict any variables that strict isnt specifically informed about (using use vars or our $var;) and isnt declared with a "my" are assumed to be lexicals that you have mistyped and thus throw an error.
The major differences between these two type of variables are as follows:
What is really cool is that lexicals can be "converted" into package variables, but package variables cannot be "converted" into lexicals:
*main::package_var=\(my $lexical_var); $lexical_var='foo'; print $main::package_var; #prints 'foo'
update: fixed a typo where i said "lexical" and meant "package".
|
|---|