DavidSzczesniak
12/15/2017 - 12:12 PM

Lexical Shadowing

Declaring a lexical in an inner scope with the same name as a lexical in an outer scope hides, or shadows the outer lexical within the inner scope.

my $name = 'Jacob';

{ 
  my $name = 'Edward';
  say $name =;
}

say $name;

# This would print Edward, then Jacob. 
# This is because the lexical in the nested scope hides the lexical in the outer scope.

# More complex example.
# Here, the lexical variable is used as the iterator variable of a for loop. 
# Its declaration occurs outside the bock, but its scope is that within the loop block:

my $cat = 'Brad';

for my $cat (qw(Jack Daisy Petunia Tuxedo Choco)) {
  say "Inner cat is $cat";
}

say "Outer cat is $cat";