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

后端 未结 3 609

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

提交回复
热议问题