[Appendix B] B.3 Closures
Author: Sriram Srinivasan
Date: 1999-07-02T01:43:17Z

#

| Appendix B Syntax Summary |

## B.3 Closures

10. An anonymous subroutine that grabs lexical variables from its containing environment is a closure. Remember that it does not just take a snapshot of the value at the instant the anonymous subroutine is seen.

        # declare an anonymous subroutine, and return a reference to it.
        my $foo = 10;
        $rs = sub {
                   print "Foo is $foo\n"; # Grabs $foo
              };
        &$rs();    # Call the closure through the reference

11. The closure keeps the grabbed variable's value around even when the variable goes out of scope.

        sub init_counter {
             my $num = shift;  # lexical variable to be grabbed
             $rs = sub { print $num++," "; };
             return $rs;
        }
        $rs_counter = init_counter(10);  # $rs_counter is a ref-to-sub
        for (1..5) {&$rs_counter()};     # Prints 10 through 14

B.2 Nested Data Structures |  | B.4 Modules