Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: lexical variable

by almut (Canon)
on Oct 06, 2009 at 15:43 UTC ( [id://799515]=note: print w/replies, xml ) Need Help??


in reply to lexical variable

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://799515]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-04-19 02:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found