Anil
Anil

Reputation: 3992

What is the difference between lexical and dynamic scoping in 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?

Upvotes: 16

Views: 7784

Answers (3)

Kevin Cox
Kevin Cox

Reputation: 3223

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.

Upvotes: 6

Sinan Ünür
Sinan Ünür

Reputation: 118148

MJD explained this in 1998:

my creates a local variable. local doesn't.

Upvotes: 11

CloudyMarble
CloudyMarble

Reputation: 37576

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:

Upvotes: 14

Related Questions