jshin has asked for the wisdom of the Perl Monks concerning the following question:
$array_ref does actually is an empty array reference but what happens to all the hash_refs? would I need to loop through the hash ref and actually set all the hash refs to {} to truly delete this array ref?my $array_ref = []; for(1 ... 10) { my $hash_ref = { foo => foo, bar => bar }; push(@{$array_ref}, $hash_ref); } $array_ref = [];
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: deleteing references
by kyle (Abbot) on Jun 09, 2008 at 02:48 UTC | |
In your example, the hash references and the original array reference are all freed when when the last line is executed. If any part of the structure contained objects, that's when their DESTROY methods would be called. Perl uses reference counting to determine when to free memory, so you mostly don't have to worry about it unless you've created a circular reference. For example:
In that case, you'd have to walk around your structure and undef the relevant references manually. Another way to handle this is with weaken in Scalar::Util. weaken makes a reference "weak" so that it doesn't count toward the reference count. With that, you can make your circular references weak, and destruction will happen normally. Note that a copy of a weak reference is not weak.
Finally, you asked about real memory being freed in a mod_perl environment. When perl releases some data structure, it doesn't necessarily return that memory to the OS. It will keep it and use it again when another data structure wants it. | [reply] [d/l] [select] |
|
Re: deleteing references
by pc88mxer (Vicar) on Jun 09, 2008 at 02:44 UTC | |
The system isn't perfect. For instance, circular references can confuse perl, but for the most part it works well enough. Some relevant pm articles on the subject: Re: undefining hashes to free memory | [reply] |
|
Re: deleteing references
by ikegami (Patriarch) on Jun 09, 2008 at 06:52 UTC | |
[] creates a new empty array and returns a reference to it. If your goal was simply to empty the array, you could use @$array_ref = (); If your goal was to free the array and the reference, you could use undef $array_ref; or let the reference fall out of scope.
| [reply] [d/l] [select] |
|
Re: deleteing references
by CountZero (Bishop) on Jun 09, 2008 at 05:18 UTC | |
CountZero A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James | [reply] |
by ikegami (Patriarch) on Jun 09, 2008 at 05:51 UTC | |
You mean like
You'll be left with the hash ref, the referenced hash, it's keys and values. Here's what happens, illustrated!
| [reply] [d/l] [select] |
by jshin (Novice) on Jun 10, 2008 at 22:25 UTC | |
| [reply] |