Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

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

by faq_monk (Initiate)
on Oct 08, 1999 at 00:27 UTC ( #694=perlfaq nodetype: print w/ replies, xml ) Need Help??

Current Perl documentation can be found at

Here is our local, out-dated (pre-5.6) version:

local($x) saves away the old value of the global variable $x, and assigns a new value for the duration of the subroutine, which is visible in other functions called from that subroutine. This is done at run-time, so is called dynamic scoping. local() always affects global variables, also called package variables or dynamic variables.

my($x) creates a new variable that is only visible in the current subroutine. This is done at compile-time, so is called lexical or static scoping. my() always affects private variables, also called lexical variables or (improperly) static(ly scoped) variables.

For instance:

    sub visible {
        print "var has value $var

    sub dynamic {
        local $var = 'local';   # new temporary value for the still-global
        visible();              #   variable called $var

    sub lexical {
        my $var = 'private';    # new private variable, $var
        visible();              # (invisible outside of sub scope)

    $var = 'global';

    visible();                  # prints global
    dynamic();                  # prints local
    lexical();                  # prints global

Notice how at no point does the value ``private'' get printed. That's because $var only has that value within the block of the lexical() function, and it is hidden from called subroutine.

In summary, local() doesn't make what you think of as private, local variables. It gives a global variable a temporary value. my() is what you're looking for if you want private variables.

See Private Variables via my() and Temporary Values via local() for excruciating details.

Log In?

What's my password?
Create A New User
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2015-10-07 22:05 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (201 votes), past polls