What is the difference between lexical and dynamic scoping in Perl?

后端 未结 3 604

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 decl

相关标签:
3条回答
  • 2021-01-04 03:48

    MJD explained this in 1998:

    my creates a local variable. local doesn't.

    0 讨论(0)
  • 2021-01-04 03:56

    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:

    0 讨论(0)
  • 2021-01-04 04:03

    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.

    0 讨论(0)
提交回复
热议问题