I needed to write a quick script today to iterate over my database and update some records. Pretty standard stuff.
If I'm having a problem with a section of code, I will usually wrap it in a "sub" statement to skip it while I figure out what is going on.
But... I noticed that when I did this and the program was finished (it prints "done" when finished) it would segfault. I reduced the script to this...
#! /usr/bin/perl use strict; use MyDB::GradeBook::Session; my $session = new MyDB::GradeBook::Session('phillup','mypassword'); sub skip_this{ $session->update_status_all(); } print "\ndone\n";
I must be having a major brain f*rt today, because I just can't see what would cause this to segfault. To make matters worse... if I remove the "sub" wrapper... the code executes as expected, does what I want... and does not segfault.
And... if I just comment out the line of code, like this:
#! /usr/bin/perl use strict; use MyDB::GradeBook::Session; my $session = new MyDB::GradeBook::Session('phillup','mypassword'); # commented out instead of wrapping in a sub # $session->update_status_all(); print "\ndone\n";
It works fine.
Any ideas why wrapping this line in a "sub" would cause a segfault?
Since the subroutine is a closure, the object won't go out of scope until the subroutine is destroyed. That tends to be quite bad news for objects with some sort of DESTROY action.
Re:Order of Destruction
phillup on 2004-01-07T02:49:36
Ah... Must review closures.
That explains why I tracked it down to a problem in the destructor of the session object. The closure would change *when* the object is being destroyed... do I have that right?
The problem goes away when I use a different serializer for my CGI::Session object, which is contained in the session object (has a, not is a). I close the CGI::Session object in the destructor of my session object.
I have not thought of subroutines being a closure... just a different lexical scope. I'm still not sure how simply using the $session variable (which is "global") in the sub changes anything, but it does seem to be something to do with object destruction.
Thanks for the input... I'll read up on closures tomorrow morning. Gotta go play with the kid...Re:Order of Destruction
phillup on 2004-01-07T03:01:45
Did some quick reading...
I didn't realize that *accessing* a variable from within a closure makes it hang around until the closure goes away. Actually, it makes sense... I simply had not thought too deeply about it.
It looks like it does this by increasing the ref count of the variable... which would definitely change when it gets destroyed.
*Now* I'll go play with the kid.;-)