[oak perl] Lexical vs. Package variables

Sandy Santra santranyc at yahoo.com
Fri Feb 4 23:15:55 PST 2005


Belden,

Thanks for the detailed response and all the examples. 
Code to play with and test! 

The perl.plover.com URL you gave me referenced an article
"Coping With Scoping" that I enjoyed very much.  Here's
the quote that nailed down one concept for me: 

"[Lexical ("my") variables are] totally inaccessible to
most parts of the program--anything outside the block where
the variable is declared.  This block is called the scope
of the variable.  If the variable wasn't declared in any
block [i.e., properly scoped], its scope is from the place
it was declared to the end of the file." 

The last sentence was really helpful.   It explains what's
going on when code is posted without any scope.  It means
the value is in effect from the "my" declaration through
the end of the script. 

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. 

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. 

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

#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

***

But of course I guess I can test this when I get home tonight.

--Sandy





More information about the Oakland mailing list