Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scope

perl

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?

like image 353
Anil Avatar asked Dec 12 '11 11:12

Anil


People also ask

What is the difference between lexical and dynamic scoping?

Answer. Lexical scoping refers to when the location of a function's definition determines which variables you have access to. On the other hand, dynamic scoping uses the location of the function's invocation to determine which variables are available.

What is lexical scoping in Perl?

The scope of a variable is the part of the program where the variable is accessible. A scope is also termed as the visibility of the variables in a program. In Perl, we can declare either Global variables or Private variables. Private variables are also known as lexical variables.

What is dynamic scoping in Perl?

Perl also supports dynamically scoped declarations. A dynamic scope also extends to the end of the innermost enclosing block, but in this case "enclosing" is defined dynamically at run time rather than textually at compile time.

What is the difference between static scoping and dynamic scoping?

In static scoping, any free variables in the function body are evaluated in the context of the defining occurrence of the function; whereas in dynamic scoping, any free variables in the function body are evaluated in the context of the function call.


2 Answers

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:

like image 135
CloudyMarble Avatar answered Oct 20 '22 14:10

CloudyMarble


MJD explained this in 1998:

my creates a local variable. local doesn't.

like image 23
Sinan Ünür Avatar answered Oct 20 '22 14:10

Sinan Ünür