http://qs1969.pair.com?node_id=635540

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

I have a daemon process which runs every n minutes. The daemon is persistent in memory and is executed via a while loop.

During each iteration of the main code body, it must connect to a database, grab some data and do something with it (the details are not important for this discussion).

i was contacted this morning by our DBAs wrt to my application having 200 connections to the database, so i went and checked the code to see if i could find the connection leak.

to my utter surprise it was due to an undef statement.

to illustrate the way the daemon is created:

my $app = Daemon->new(sleep => 60, mailLimit => 200); while (1) { $app->doSomething(); print scalar(localtime)." Sleeping 300 seconds...\n"; sleep 300; }

inside the Daemon object is a call to create a database object (which creates the db connection) and assigns it to $self->{dbo}

the code i use to create the database object checks for the existence of $self->{dbo}, and if it exists re-uses it, if not, creates it.

to force the creation of a new database object each time (for reasons i cant remember now - yes i should have used comments in the code :-) ) i did an undef on the $self->{dbo} variable.

the expected result is that once i undef the $self->{dbo} variable, it would fall out of scope and the database connection would be implicitly released.

in practice this is not the case. it seams that once the variable has been undef'd it is left dangling in memory and not cleaned up.

while this seems pretty black and white based on what i've observed, as mentioned, it was totally unexpected.

can anyone explain why?