๐Ÿ“˜ Lexical variables in Perl 6

Lexical variables in Perl 6 are those declared with the my keyword. These variables are only visible within the block where they were declared. If you tried accessing them outside the scope, youโ€™d get the error: Variable ‘$x’ is not declared.

ย ย ย ย  my $x = 42;
ย ย ย ย  say $x; # This is fine
# say $x;ย ย  ย # This is not

To โ€œextendโ€ the scope, lexical variables can be used in closures. In the following example, the seq sub returns a block, which uses a variable defined inside the sub.

sub seq($init) {
ย ย ย ย  my $c = $init;
ย ย ย ย  return {$c++};

The sub returns a code block containing the variable $c. After the subโ€™s execution, the variable will not only still exist but also will keep its value, which you can easily see by calling a function by its reference a few times more.

my $a = seq(1);

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

It is possible to create two independent copies of the local variable.

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

To see how it works, call the subs a few times:

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s