|Syntactic Confectionery Delight|
Re: Non-programmers and variable scopeby jonadab (Parson)
|on Apr 28, 2007 at 18:18 UTC||Need Help??|
In the first place, packages aren't really scope. They're namespace. Package variables have exactly the same scope as global variables. All you really have to explain about them, then, is that if the package namespace isn't specified, the current package is implied, or main if you haven't specified a package. Other than that naming issue, they're just global.
In the second place, most new programmers already have a pretty good understanding of global scope. (Actually, it's really process scope (or possibly thread scope if you're into that sort of perversion), but nevermind: most new programmers understand it well enough.)
So that really just leaves you explaining the difference between lexical scope and dynamic scope. And it's a pretty simple difference, in principle: with dynamic scope, other code that you call will see (and set, if applicable) your dynamic value. With lexical scope, that's not the case.
Of course, this simple difference in how lexical and dynamic scope work leads to larger differences in terms of how they are typically used. Lexical scope (my in Perl) is typically used to avoid having your private variables trompled on by other code; whereas, dynamic scope (local in Perl) is most often used to change the behavior of other code that you are calling, by temporarily changing the values of some of its variables. So if you want a function you are calling (say, print) to behave in a different way from the usual, you might use local to dynamically scope one of its variables (such as $/ for instance), but if you don't want other code that's calling you to mess with your private variables, you might use my to scope them lexically to your function or block.
The real confusion comes from the use of the word local. Most people hear the word "local" and think "local to this function", "local to this block", or something along those lines, but in fact that's lexical scope, which is what my does. The Perl keyword local does dynamic scope, which isn't really local at all, except temporally.
We're working on a six-year set of freely redistributable Vacation Bible School materials.