Lexical variables

Lexical variables belong to their scope. If it is defined within a block of code (for instance, inside a subroutine), it is only visible and accessible inside it.

{
    my $x = 42;
    say $x; # OK
}

#say $x; # Not OK

The second attempt to use $x here will fail because there is no such variable outside the block above.

Similarly, it works with variables defined inside subroutines:

sub f() {
    my $x = 42;
    say $x;
}

f(); # OK
#say $x; # Error

Nothing changes when the variable is declared as a state one:

sub f() {
    state $x = 42;
    say $x;
}

f(); # OK
#say $x; # Error

Note that if you create a closure, the actual scope of a variable will be extended. In the following example a subroutine returns a block containing its lexical variable. Thus, it can be used later in the programme outside the subroutine where the variable was declared:

sub seq($init) {
    my $c = $init;

    return {$c++};
}

my $a = seq(1);

say $a(); # 1
say $a(); # 2
say $a(); # 3

Each time, the $a() call increments exactly the same variable, only visible inside the seq() subroutine.

Moreover, it is possible to create more than one closures, each containing its own container with the counter:

sub seq($init) {
    my $c = $init;

    return {$c++};
}

my $a = seq(1);
my $b = seq(42);

say $a(); # 1
say $a(); # 2
say $b(); # 42
say $a(); # 3
say $b(); # 43

In Perl 6, the operations returning dynamicly-behaving blocks with lexically-defined variables are called lexotic. These are return, next, last, redo and goto.