DavidSzczesniak
12/15/2017 - 10:51 AM

Lexical Scope

This is the scope apparent to the readers of the program. It describes visibility of variables declared with my - lexical variables.

# A lexical variable declared in one scope is visible in that scope and any nested within it, 
# but is invisible to sibling or outer scopes:

# outer lexical scope 
{   
    package Robot::Butler
    
    # inner lexical scope
\!h    my $battery_level; # visible in all 4 scopes
    
    sub tidy_room {
      #further inner lexical scope
\!h      my $timer; # visible in the method, do block and for loop
      
      do {
        # innermost lexical scope
\!h        my $dustpan; # only visible in the do block
        ...
      } while (@_);
      
      # sibling inner lexical scope
      for (@_) {
        # separate innermost scope
\!h        my $polish_cloth; # only visible in the for loop
        ...
      }
    }
}