in reply to The difference between my and local
"'local' temporarily changes the value of the variable, but only within the scope it exists in."What does it mean? What's this "scope" they keep telling you about?
Here's a nice way to distinguish my from local.
then %z,@y,$x are the temporary ones from declaration (point (1)) to the end of the block (point (4)). In particular, the call to foo (point (2)) can see all three variables, because foo was defined within the scope. The call to bar (point (3)) can't see @y,%z, because bar is defined outside the block's scope. Of course, that particular call can see $x as a parameter.{ # ... my ($x, @y, %z); # (1) # ... sub foo { # ... } # ... foo(17); # (2) bar($x,29); # (3) # ... } # (4) # ... sub bar { # ... }
Note how easy it is to tell the scope of a `my' declaration: it's a lexical thing. All you have to do is look for the end of the block (point (4)). The `my' variable is visible from its declaration to the end of the block, and nowhere else.
then the global variables $x,@y,%z (declared in the use vars pragma) are given temporary versions at point (5). These temporary versions are in effect until execution reaches the end of the block (point (8)), at which time the old versions come back.use vars qw/$x, @y, %z/; { # ... local ($x, @y, %z); # (5) # ... sub baz { # ... } # ... baz(17); # (6) quux($x,29); # (7) # ... } # (8) # ... sub quux { # ... } # ... baz(29); # (9)
It doesn't matter that baz is defined inside the block. The call at point (6) uses the temporary versions, because it happens (in time!) between (5) and (8); the call at point (9) uses the original versions, because it happens (in time!) after (8). The call to quux can see the temporary versions of all 3 variables, even though the definition of quux occurs outside the variable. What matters is that the call occurs during the temporary scope.
|
---|