[San-Diego-pm] Deleting package from memory
Daniel Risse
dan at tierra.net
Tue Apr 10 10:17:34 PDT 2007
Hello,
This is to follow up to what Urivan was discussing last night. I looked
and Symbol does in fact define the delete_package() function. There is
a warning in the documentation regarding it though:
> Symbol::delete_package is a bit too powerful. It undefines every
> symbol that
> lives in the specified package. Since perl, for performance reasons,
> does not
> perform a symbol table lookup each time a function is called or a global
> variable is accessed, some code that has already been loaded and that
> makes use
> of symbols in package Foo may stop working after you delete Foo, even if
> you reload the Foo module afterwards.
There is also something that strikes me as a bit wrong about loading an
additional module to assist unloading other modules. The function could
be copied and modified to also clear out the %INC entry for the module.
> sub delete_package ($) {
> my $pkg = shift;
>
> # expand to full symbol table name if needed
>
> unless ($pkg =~ /^main::.*::$/) {
> $pkg = "main$pkg" if $pkg =~ /^::/;
> $pkg = "main::$pkg" unless $pkg =~ /^main::/;
> $pkg .= '::' unless $pkg =~ /::$/;
> }
>
> my($stem, $leaf) = $pkg =~ m/(.*::)(\w+::)$/;
> my $stem_symtab = *{$stem}{HASH};
> return unless defined $stem_symtab and exists $stem_symtab->{$leaf};
>
>
> # free all the symbols in the package
>
> my $leaf_symtab = *{$stem_symtab->{$leaf}}{HASH};
> foreach my $name (keys %$leaf_symtab) {
> undef *{$pkg . $name};
> }
>
> # delete the symbol table
>
> %$leaf_symtab = ();
> delete $stem_symtab->{$leaf};
> }
Dan
More information about the San-Diego-pm
mailing list