The binding of lexical (my) variables can be determined by mere lexical analysis (reading/parsing) of the program. Their binding does not depend on the runtime dynamics of the program. This is thus sometimes also called static scoping. In contrast, there is also dynamic scoping of package variables in Perl. Both types can be employed to have "local" variables. An example to demonstrate:
#!/usr/bin/perl $foo = 42; sub func { print "$foo\n"; } { # new local scope my $foo = 99; # lexical variable, statically scoped func(); # -> 42 } { # new local scope local $foo = 99; # package variable, dynamically scoped func(); # -> 99 }
The first call to func() prints 42, even though the value of $foo has been set to 99 for the local lexcial scope (the block specified by the curlies). This is because the $foo within func() is outside of that lexical scope and thus does not bind to the my $foo variable. Rather, it binds to the package variable $foo, which has been initialised to 42.
The second call to func(), however, prints 99, because the value of the package variable $foo has been set to 99 for the local dynamic execution context of func() within the respective scope (again, the block). In other words, the actual value that $foo within func() binds to in this case depends on the runtime dynamics of the program, which typically cannot be determined by mere lexical analysis.
In reply to Re: lexical variable
by almut
in thread lexical variable
by manishrathi
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |