What is the difference between lexical and dynamic

2020-03-01 06:09发布

问题:

As far I know, the my operator is to declare variables that are truly lexically scoped and dynamic scoping is done using the local operator to declare a variable.

Can any one describe them in brief?

回答1:

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 it is called lexical or static scoping. my() always affects private variables, also called lexical variables or (improperly) static(ly scoped) variables.

Take a look at the Perl-FAQ's:



回答2:

MJD explained this in 1998:

my creates a local variable. local doesn't.



回答3:

I'll add a quick example.

$var = "Global";

sub inner {
    print "inner:         $var\n";
}

sub changelocal {
    my $var = "Local";
    print "changelocal:   $var\n";

    &inner
}

sub changedynamic {
    local $var = "Dynamic";
    print "changedynamic: $var\n";

    &inner
}

&inner
&changelocal
&changedynamic

This gives the following output (comments added).

inner:         Global  # Finds the global variable.
changedynamic: Dynamic # Dynamic variable overrides global.
inner:         Dynamic # Find dynamic variable now.
changelocal:   Local   # Local variable overrides global.
inner:         Global  # The local variable is not in scope so global is found.

You can think of a dynamic variable as a way to mask a global for functions you call. Where as lexical scoped variables only be visible from code inside the nearest braces.



标签: perl scope