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

Get Advanced Perl Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.