home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


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 Structures Advanced Perl Programming Next: B.4 Modules
B.2 Nested Data Structures Book Index B.4 Modules

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.