Advanced Perl Programming

Advanced Perl ProgrammingSearch this book
Previous: B.2 Nested Data StructuresAppendix B
Syntax Summary
Next: B.4 Modules
 

B.3 Closures

  1. 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
                
  2. 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


Previous: B.2 Nested Data StructuresAdvanced Perl ProgrammingNext: B.4 Modules
B.2 Nested Data StructuresBook IndexB.4 Modules