http://www.perlmonks.org?node_id=47758


in reply to Re: typeglobs and filehandles
in thread typeglobs and filehandles

Let me start off by saying thank you for such a well written response! You have clarified and verified my understanding of a lot of whats going on.

Dominus says:
> Variables do not have scope. Instead, they have duration.
>The duration of a variable is the period of time in which
>memory is allocated for the variable. In Perl, a variable's
>duration continues until there are no more references to it, at
>which point it is destroyed.

This makes sense. Perl doesnt dispose of a variables value in memory untill there are no more references to it. This seems to be convenient. However.. I was wondering if this could cause problems in the situation of say a Linked List. Since the list would have references to other nodes in the list, you would think you would have to traverse the structure to release the memory. So of course I made another test:

#!/usr/bin/perl -w sub add_node { my $tmp = { }; my $prev = shift; $tmp->{'prev'} = $prev; $tmp->{'data'} = shift; $prev->{'next'} = $tmp; return $tmp; } my $pos = { data => 0 }; { my $cur = $pos; for my $x (1..1000000) { $cur = add_node($cur, $x); } } while ($inp ne "quit") { print "DATA: $pos->{'data'}\n"; $inp = <STDIN>; chomp $inp; if ($inp eq '>') { $pos = $pos->{'next'} if exists ($pos->{'next'}); }elsif ($inp eq '<') { $pos = $pos->{'prev'} if exists ($pos->{'prev'}); } } sleep (10); print "\$pos = undef\n"; $pos = undef; sleep (10); $pos = "zzSPECTREz"; print "\$pos = $pos\n"; sleep (10); print "make new linked list with \$pos\n"; { my $cur = $pos; for my $x (1..100000) { $cur = add_node($cur, $x); } } sleep(10);

Now I open Windows Task Manager to watch memory usage of perl with this script. As the script builds the list perls memory usage grows significantly and settles at 68,820k. Using the '<' and '>' keys I navigate the list verify it works. Then type quit. First the $pos variable is set to undef. No change in memory usage. Then it is set to the text 'zzSPECTREz' no memory change. Then we build a new smaller linked list. At this point the memory usage shrinks to about 12,400k. Hmmm.

This leaves me confused on whats happening. I thought that a memory leak would be caused since I was destroying my reference to my linked list but since the list had references to itself perl would not release the memory. This would make sense. The test program seems to prove this when memory is not released when I change the value of my pointer to my list. However the memory does release when I build a new list using that variable.. Why?

thank you for your explanations!
zzSPECTREz