in reply to Closure Confusion

++Thanks to all who replied. I think I've got this. It's not the value of the lexical that's captured by the closure, it's the instance, as the following illustrates:

sub make_closures { my $j = shift; return (sub {++$j;}, sub {print $j, "\n";}); } my ($bump1, $print1) = make_closures(5); my ($bump2, $print2) = make_closures(10); &$print1; &$bump1; &$print1; &$print2; &$bump2; &$print2;

which prints

5 6 10 11

I.e., each call to make_closures creates an instance of $j which is shared by bump and print, but unique to each call to make_closures. Hmmm. The ability to create at runtime multiple instances of a a thingy encapsulating data and behaviour. Sounds like the road to Objects.

In other news: sorry about the typo, I was rushing out the door ("But PerlMonks is work related"). Should've waited until the morning.

Chromatic: I know that calling &sub turns off parameter checking -- it is that you warn of?

Again, Thanks to all.

-- Dinosaur

Replies are listed 'Best First'.
Re^2: Closure Confusion
by Aristotle (Chancellor) on Oct 18, 2002 at 12:39 UTC
    Sounds like the road to Objects.
    Or actually, something like the reverse of objects: code which data is associated to, rather than data which code is associated to.
    I know that calling ⊂ turns off parameter checking -- it is that you warn of?
    Calling a function as &function; passes the current @_ on to it. You should write &function(); if you mean to simply call it.

    Makeshifts last the longest.