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

后端 未结 3 581

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 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.

提交回复
热议问题