LPM: Packages and persistence.

David Hempy hempy at ket.org
Mon May 21 21:23:04 CDT 2001


Okay...I'm migrating a system into PerlEX (ActiveState's answer to modPerl), and seeing some nifty performance increases.  I'm running into a little bit of unwanted variable persistence.  For the most part, I'm okay because I always use strict and initialize my variables.

However, I use some explicit package variable in conjunction with Text::Template.  For example, $TEMPLATE::table_rows .= "<tr>...</tr>";

I started to initialize all these variable at the start of each invocation, which would work just fine.  Problem is, I don't trust myself to catch them all.  Plus, they'll be hanging around taking up memory in the meantime, and a particularly bad memory leak situation if I continually append to the variable.


Soooo....

What I want to do is systematically initialize all the variables in a package at startup.  (I guess at shutdown would be even better.)  I've got it pretty well licked by messing around in the symbol table.  The following code demonstrates this.  The juicy part is in PurgePackage(), which is lifted largely from the Camel book's package chapter.



$hello='FROM MAIN';

$TEMPLATE::hello='FROM TEMPLATE';
$TEMPLATE::now='then';

DumpPackage('main::TEMPLATE::');
PurgePackage('main::TEMPLATE::');
DumpPackage('main::TEMPLATE::');



sub DumpPackage {
	($pkg) = @_;
	
	print "package: $pkg\n";
	foreach $var (sort keys %{$pkg}) {
		$var = "$pkg$var";
		print " \$$var -> " . ${$var} . "\n";
	}
	print "\n";
}

sub PurgePackage {
	($pkg) = @_;
	
	print "package: $pkg\n";
	foreach $var (sort keys %{$pkg}) {
		$var = "$pkg$var";
		print " undef \$$var\n";
		undef $$var;
	}
	
	print "undef \$$pkg\n";
	undef $$pkg;
	
	print "\n";
}




Running this yields:



package: main::TEMPLATE::
 $main::TEMPLATE::hello -> FROM TEMPLATE
 $main::TEMPLATE::now -> then

package: main::TEMPLATE::
 undef $main::TEMPLATE::hello
 undef $main::TEMPLATE::now
undef $main::TEMPLATE::

package: main::TEMPLATE::
 $main::TEMPLATE::hello -> 
 $main::TEMPLATE::now -> 


I'm happy that the values of each variable get wiped out, but a bit surprised that they still exist at all.  Doesn't undef pretty much wipe a variable out of existance?  Am I missing a concept about variables and symbol tables?


On a larger scale, am I missing the big picture?  Only after finishing the previous paragraph did I return back to the Text::Template docs, and now I'm wondering if a hash would work better than a package for persistence issues.  With a hash, I could just undef the whole thing or let it go out of scope without a problem.  Any thoughts from folks who have had similar adventures with modPerl or PerlEX?


-dave



-- 
David Hempy 
Internet Database Administrator
Kentucky Educational Television - Distance Learning Division
<hempy at ket.org> -- (859)258-7164 -- (800)333-9764





More information about the Lexington-pm mailing list