[Chicago-talk] The "other" closure

Jim Thomason jthomasoniii at yahoo.com
Wed Dec 3 12:46:14 CST 2003


> This is a really nice example of a private static
> variable, but it is not a closure. The difference
> is that all invocations of the foo sub here will
> share the same value of $static.

All invocations of an anonymous subroutine that refers
to an out-of-scope lexical will share the same lexical
values as well. :)

Remember - a subroutine generator does just that. It
generates subroutines. So you get back lots of
different subroutines with lots of different lexicals
hidden within them.

The only difference here is that I'm only creating one
closure instead of (potentially) a whole bunch of
them.

If you're only creating one of them, then I fail to
see the reason to do:

sub foo_maker {
 my $static = 0;
 return sub foo {
  #do something interesting with $static;
 };
};

my $foo = foo_maker();
$foo->();

instead of:

{
 my $static = 0;
 sub foo {
   #do something interesting with $static;
 }
};

foo();

Sure, you need a subroutine generator if you want
multiple functions referring to different lexicals,
but there's no number limit on closures. If you only
use one of them, it's still a closure. If you're only
using one, you might as well just declare the function
instead of going through the function generation
routines.
 
> That's what makes them a closure: the storage used
> in the
> anonmous subroutine is private to the specific
> instance;
> creating multilpe anonymous subroutines gives each
> of them
> their own storage.

Absolutely. :)

That's what I said..."the important bit about a
closure is the fact that it refers to a lexical that
can't be accessed from anywhere except for within the
subroutine. "

The fact that it's an anonymous subroutine is beside
the point. The fact that it's the only thing that can
see a particular lexical -is- the important part.

Function generation is a side point.

And I still say that it's more important to focus on
the Important Piece (functions that see otherwise
invisible lexicals) and then worry later about ways to
use it (such as creating anonymous functions or
generating lists of functions or whatever). The former
is the tool (the closure), the latter is an example of
a way to use it.

-Jim......

__________________________________
Do you Yahoo!?
Free Pop-Up Blocker - Get it now
http://companion.yahoo.com/



More information about the Chicago-talk mailing list