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:

  1. package variables dont need to be declared _ever_. use vars and our actually arent declarations in the traditional sense, they are actually pragmatta that alter the behaviour of strict, they dont alter the behaviour of package variables at all.
  2. lexical variables MUST ALWAYS be declared. If you havent declared it with a my then it isnt a lexical.
  3. lexical variables are faster than package variables. With deeply nested namedspaces and FQ notation much faster.
  4. package variables are dynamically scoped. This means that you can use the local keyword for them.
  5. package variables require more space
  6. package statements change how package variables are dealt with Perl, package statements have nothing at all to do with lexical variables.

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

---
demerphq