Perl FAQ 4.4: What's the difference between deep and shallow binding?

Perl FAQ 4.4

What's the difference between deep and shallow binding?

5.000 answer:

This only matters when you're making subroutines yourself, at least so far. This will give you shallow binding:

      my $x = time;
      $coderef = sub { $x };

When you call &$coderef(), it will get whatever dynamic $x happens to be around when invoked. However, you can get the other behaviour this way:

      my $x = time;
      $coderef = eval "sub { \$x }";

Now you'll access the lexical variable $x which is set to the time the subroutine was created. Note that the difference in these two behaviours can be considered a bug, not a feature, so you should in particular not rely upon shallow binding, as it will likely go away in the future. See perlref(1) .

5.001 Answer:

Perl will always give deep binding to functions, so you don't need the eval hack anymore. Furthermore, functions and even formats lexically declared nested within another lexical scope have access to that scope.

    require 5.001;

    sub mkcounter {
    my $start = shift;
	return sub {
	    return ++$start;

    $f1 = mkcounter(10);
    $f2 = mkcounter(20);
    print &$f1(), &$f2(); 
11 21
    print &$f1(), &$f2(), &$f1();
12 22 13

See the question on ``What's a closure?''

Other resources at this site: