Course of Raku / Advanced / Subroutines / Nested subroutines / Exercises / Closing over the outer
Solution: Closing over the outer
Here is a possible solution to the task.
Code
sub greet($name) {
sub message {
"Hello, $name!";
}
say message;
}
greet('Anna');🦋 You can find the source code in the file closure-over-outer.raku.
Output
Hello, Anna!Comments
messagetakes no arguments, yet it can use$name. A nested subroutine closes over the lexical variables of the subroutine that contains it, so the outer$nameis in scope.When
greet('Anna')runs,$nameis'Anna', somessagereturnsHello, Anna!. This sharing of the enclosing scope is what makes nested helpers more than just hidden functions.