Socrates has asked for the wisdom of the Perl Monks concerning the following question:

Let's say I have a function that creates anonymous subs and spits out coderefs to them, and that I'm using a closure to create an analogue of a static variable (somewhat akin to what Memoize does):
sub subfactory { my $static = int(rand(100)); return sub {print "my number is $static\n";} }
Then, I simply assign the function to a scalar, call it and undef it:
my $func=subfactory(); $func->(); undef $func;
My question is as follows: is the memory reserved for each instance of $static freed when I undef the function? I would imagine that the anonymous sub compiled in memory contains the sole ref to the memory that was set aside when $static was defined in subfactory() and that, when I undef the function, the reference would be freed too, freeing the memory up for garbage collection, but I'm not sure if that's an accurate assessment, and certainly more info on the internals would be appreciated.

Also what kind of code could I call to illustrate how this works?

Replies are listed 'Best First'.
Re: When are references within a closure freed?
by Fletch (Bishop) on Sep 05, 2008 at 17:15 UTC

    A victim object with a destructor can be your instructor.

    package Canary; sub new { return bless {}, shift(); } sub DESTROY { warn "*CHEEP* *GASP*"; } package main; END { warn "END BLOCK\n"; } $| = 1; my $closure; { my $boid = Canary->new(); $closure = sub { $boid = $boid; warn "Fweee\n"; }; } $closure->(); warn "Pre undef\n"; undef $closure; warn "Post undef\n"; exit 0; __END__ $ perl spoozle Fweee Pre undef *CHEEP* *GASP* at spoozle line 4. Post undef END BLOCK

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.