In this section, we will learn three techniques that can change the scope of variables. These are closures, currying, and dynamic scoping.
Manipulating the scope
Closures
In Perl 6, lexical variables exist within their scope. Closures are functions that can extend that scope and let you access the lexical value, which were available at the place where the closure was defined. Let us consider an example of the counter that keeps the current state in a variable.
First, no closures are involved. The counter value is kept in a global variable:
my $counter = 0;
sub next-number() {
return $counter++;
}
say next-number(); # 0
say next-number(); # 1
say next-number(); # 2
Each time the next-number function is called, an increasing integer...