Perl FAQ 4.3: What's the difference between dynamic and static (lexical) scoping?

Perl FAQ 4.3

What's the difference between dynamic and static (lexical) scoping?

What are my() and local()?
[NOTE: This question refers to perl5 only. There is no my() in perl4]
Scoping refers to visibility of variables. A dynamic variable is created via local() and is just a local value for a global variable, whereas a lexical variable created via my() is more what you're expecting from a C auto. (See also ``What's the difference between deep and shallow binding.'') In general, we suggest you use lexical variables wherever possible, as they're faster to access and easier to understand. The ``use strict vars'' pragma will enforce that all variables are either lexical, or full classified by package name. We strongly suggest that you develop your code with ``use strict;'' and the -w flag. (When using formats, however, you will still have to use dynamic variables.) Here's an example of the difference:

    $myvar = 10;
    $localvar = 10;
    print "Before the sub call - my: $myvar, local: $localvar\n";

    print "After the sub call - my: $myvar, local: $localvar\n";


    sub sub1 {
	my $myvar;
	local $localvar;

	$myvar = 5;     # Only in this block
	$localvar = 20; # Accessible to children

	print "Inside first sub call - my: $myvar, local: $localvar\n";

    sub sub2 {
	print "Inside second sub - my: $myvar, local: $localvar\n";


Notice that the variables declared with my() are visible only within the scope of the block which names them. They are not visible outside of this block, not even in routines or blocks that it calls. local() variables, on the other hand, are visible to routines that are called from the block where they are declared. Neither is visible after the end (the final closing curly brace) of the block at all.

Oh, lexical variables are only available in perl5. Have we mentioned yet that you might consider upgrading? :-)

Other resources at this site: