Skip to content

Commit ea84e6c

Browse files
committed
Attempt to explain lexical scope
1 parent 08bc0fd commit ea84e6c

File tree

1 file changed

+72
-2
lines changed

1 file changed

+72
-2
lines changed

lib/Language/variables.pod

Lines changed: 72 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -336,11 +336,81 @@ There are also two listops that resemble declarators, but act on
336336
predefined variables:
337337
338338
=for table
339-
Listop
340-
======
339+
Listop Effect
340+
====== ======
341341
temp Restores a variable's value at the end of scope
342342
let Restores a variable's value at the end of scope if the block exists unsuccessfully
343343
344+
=head2 The C<my> Declarator
345+
346+
Declaring a variable with C<my> gives it lexical scope. This means
347+
that it only exists within the current block. For example:
348+
349+
{
350+
my $foo = "bar";
351+
say $foo; # -> "bar"
352+
}
353+
say $foo; # !!! "Variable '$foo' is not declared"
354+
355+
This dies because C<$foo> is only defined as long as we are in the same scope.
356+
357+
Additionally, lexical scoping means that variables can be temporarily
358+
redefined in a new scope:
359+
360+
=begin code
361+
my $location = "outside";
362+
363+
sub outer-location {
364+
# Not redefined:
365+
say $location;
366+
}
367+
368+
outer-location; # -> "outside"
369+
370+
sub in-building {
371+
my $location = "inside";
372+
say $location;
373+
}
374+
375+
in-building; # -> "inside"
376+
377+
outer-location; # -> "outside"
378+
=end code
379+
380+
If a variable has been redefined, any code that referenced the outer
381+
variable will continue to reference the outer variable. So here,
382+
C<&outer-location> still prints the outer C<$location>:
383+
384+
=begin code
385+
sub new-location {
386+
my $location = "nowhere"
387+
outer-location;
388+
}
389+
390+
new-location; # -> "outside"
391+
=end code
392+
393+
To make C<new-location()> print C<nowhere>, make C<$location> a
394+
dynamic variable using L<the * twigil|#The_*_Twigil>.
395+
396+
=head2 The C<our> Declarator
397+
398+
=head2 The C<has> Declarator
399+
400+
=head2 The C<anon> Declarator
401+
402+
=head2 The C<state> Declarator
403+
404+
=head2 The C<state> Declarator
405+
406+
=head2 The C<augment> Declarator
407+
408+
=head2 The C<supersede> Declarator
409+
410+
=head2 The C<temp> Listop
411+
412+
=head2 The C<let> Listop
413+
344414
=head1 Special Variables
345415
346416
=head2 Often-Used Variables

0 commit comments

Comments
 (0)