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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.