[oak perl] Lexical vs. Package variables

Zed Lopez zed.lopez at gmail.com
Mon Feb 7 17:21:30 PST 2005


> But now I'm grappling with the *basic* idea of scoping:
> that you're cordoning off a part of your script with a scoped
> value so that a variable with an identical name elsewhere
> in the code is unaffected.
> 
> This actually seems pointless, if I'm foolish enough to
> believe that a script is always a linear affair, like driving
> a car past scenery.

It doesn't have much point for a very short script. It is immensely
pointful for anything longer, though.

For instance, if you couldn't scope your variables, you'd have to
double-check by hand that you weren't re-using variable names among
different subroutines.
 
> But somewhere in the back of my mind--sorry to get existential
> here--I recall seeing loops or "subs" set up at the beginning
> of a long script that would "trigger" when a certain condition
> suddenly got satisfied somewhere in the middle of the script.
>  In a way, doesn't that take programming out of the two-dimension
> lity of a "train on a track going somewhere" to a universe
> of simultaneity (random events can trigger and run simultaneously
> ?  And if IF and/or WHEN loops can be triggered anywhere
> in a program, then I can very definitely see the point of
> having lexical variables in order to lock down their values
> within their scopes.

You're thinking of event-driven programming here, for instance through
signals. But it's as deterministic as any other programming, just more
complicated. Lexically scoped variables are no more or less relevant
in this case than for any other complicated program.

> Coming back down to earth, and trying to understand the
> advantages of lexical variables, how about this example
> as a demonstration of some basic concepts involved:
> 
> #TEST1 -- lexical trumps package
> 
> sub standard {
>         my $x = red;
>         print "x\n"; # should print red
> }
> 
> print "x\n"; # should print only newline

I assume you mean print "$x\n" in both cases. In the latter case,
you'll get an error if you've used strict (as you should for any
non-trivial program.) If you haven't, you're correct.

> #TEST2 package trumps lexical
> 
> $x = pink;
> print "x\n"; # should print pink
> 
> sub marine {
>         my $x = blue;
>         print "x\n"; # should print blue
> }
> 
> print "x\n"; # should print pink

Same as above. Assuming you meant "$x\n", you're right, but it won't
run under use strict.

Zed


More information about the Oakland mailing list