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

Hi,

I'm using a hash whose keys store object references. Can I simply delete that key or do I need to undef the object reference to make sure the objects are garbage collected? The hash stays in scope but the object was declared lexically scoped earlier in a subroutine and assigned to the value of a hash:

use Foo::Object; my %hash = (); &somesub; # does this garbage collect the object? delete $hash{'object'} if exists $hash{'object'} sub somesub { $hash{'object'}=new Foo::Object; }
Is there anything that I would need to specifically undef before deleting such a key? Are there other issues here, or am I just confused?

Thanks.

Edit by tye

Replies are listed 'Best First'.
Re: Garbage collection
by bikeNomad (Priest) on May 31, 2001 at 23:09 UTC
    Deleting it from the hash should work by itself. Also, you can call delete without checking existence first.

    Where you have to worry about garbage collection is if you have circular object references in the value of the hash:

    my $a = { }; my $b = { a => $a }; $a->{b} = $b; $hash{something} = $a; delete $hash{something};
    In cases like these, you should break the circular references before the delete.