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

I have a class, with a member variable "A" that's an array reference. the array holds references to hash tables. currently, the array is a package level variable, although i'm not against changing this to a "self" variable. anyways, what is the best way to free all the hash references in the array, and the array from memory in "cleanUp?"
package MyObject; my @a = (); sub new { my $class = shift; my $self = {}; bless $self, $class; return $self; } sub A { my $self = shift; return \@a; } sub fillIt { my $self = shift; my %hash = (); my $i = 0; for($i=0; $i<10; $i++) { $hash{"key_$i"} = $i; } push(@a, \%hash); } sub cleanUp { my $self = shift; #?????????????????????????????????????????????????? # best way to deref entire @a? #?????????????????????????????????????????????????? } return 1;

Replies are listed 'Best First'.
Re: Dereferencing question
by ikegami (Patriarch) on Sep 01, 2009 at 23:54 UTC

    You can empty @a any time you want to by assigning an empty list to it. If nothing else references the hashes referenced by @a, that will free them.

    As for removing @a itself from memory? Not until every reference to it disappears. Subs A and fillIt reference it, so those subs would need to be freed to remove @a from memory.

Re: Dereferencing question
by stevieb (Canon) on Sep 01, 2009 at 23:32 UTC

    How are you using @a outside of the object?

    Generally, cleaning this up would be done by either the implicit or a custom DESTROY(). However, if you are returning the ref to an outside program, then (correct me if I'm wrong) Perl can't destroy it, because there are still references to it. AFAIK, Perl won't allow 'dangling pointers', but I've never tested this in your context.

    For that matter, I don't even know if your cleanUp() could wreck the reference that the package gave out, as it doesn't even belong to the object of the package. Perhaps someone could clarify this.

    Furthermore, hopefully your variables are named as such for example only, because I've been smacked around a few times for using @A and 'sub A' etc ;)

    Steve

      Here's some example usage; the references shouldn't in "doSomething" go away when you go out of it's (sub doSomething)'s scope?
      use MyObject; # -------------------------------- # main.pl # -------------------------------- my $object = undef; $object = new MyObject; $object->fillIt(); doSomething($object->A); sub doSomething { my $arrayReference = shift; foreach my $hashReference (@$arrayReference) { # do something } } $object->cleanUp(); exit 0;
      so you are saying:
      @a = ();
      will clean up all the hashreferences in @a?