> >> The perlref docs state "Hard references are smart--they keep track of
> >> reference counts for you, automatically freeing the thing referred to
> >> when its reference count goes to zero."  My interpretation of this is
> >> that when a reference goes out of scope the memory used by 
> >> the referent is freed.  
> >> 
> >> <snip>
> 
> > Yes and no.  From what I understand (and someone please correct me if
> > I'm wrong), the memory is freed in the sense that it is returned to
> > Perl, but it is not returned to your system.  Once there are no
> > references to a variable, the memory can be overwritten by future
> > variables used in your program, but cannot be used by other programs. 
> 
> I wasn't as concerned about whether perl or the system can access the
freed
> memory (although maybe I should be) - I was more interested in what
happens
> to the memory used by the old referent when the reference that points
to it
> is changed to point to a new referent (see example below).  The
variable (the
> reference) maintains the same count as it did before the change, but the
> block of memory used by the first referent is now orphaned (or is
it??).  So
> I guess my question becomes: does perl track the number of references to a
> referent so it knows when it (the referent) is no longer accessible?  I'm
> beginning to think that this is the case, but I want to make sure so I
don't
> write a lot of memory-wasting code.
> 
> foreach my $term ( @list )
> {
>       my $hashref = makehash( $term );
> 
>       # do stuff with $hashref
> 
>       $term = $term . '2';
> 
>       $hashref = makehash( $term );
> 
>       # do more stuff with $hashref
> }
> 

I believe your last description is correct.  The number counting is to
the referent(s) not the storing variable. So as soon as you have no way
to refer to a particular data structure (memory, referent, etc.)(your
"orphaned" stuffs) then Perl will collect it.  This is sufficient in
most cases, and generally proper scope limiting will make it easy not to
need to worry about this.  There are other more explicit ways to
manipulate Perl's reference counting, specifically see Scalar::Util and
it's 'weaken' method, this is good practice when using circular
references or the like.

Of course remember that a variable that stores a reference can (is?)
also a referent. Aka, 

my %hash = ();
my $reference_holder = \%hash;
my $reference_to_reference_holder = \$reference_holder;

:-)....

perldoc perlref

http://danconia.org

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to