September 2017
Beginner
402 pages
9h 52m
English
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(); # 0say next-number(); # 1say next-number(); # 2
Each time the next-number function is called, an increasing integer number is returned.
Now, the goal is to hide the $counter variable so that it is not accessible directly to the user of next-number. Here comes a closure. First, both the variable ...