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

Why is it that I always think up questions in code first? Don't answer:
my(@arr); { my %var; $var{"love"}="Anthing goes"; $arr[0]=\%var; } print $$arr[0]{"love"};
Now will it print "Anything goes", or will the hash drop from under the reference, and confuse Perl? I'm wondering if the use of my is similar to C++'s new()...

--
$Stalag99{"URL"}="http://stalag99.keenspace.com";

Replies are listed 'Best First'.
Re: Dissapearing from under one's reference
by danger (Priest) on Mar 28, 2001 at 11:29 UTC

    Well, it won't print 'Anything goes' for 2 reasons: the dereferencing is incorrect, and the value does not hold 'Anything goes' :-)

    my(@arr); { my %var; $var{"love"}="Anthing goes"; $arr[0]=\%var; } print ${$arr[0]}{love},"\n"; print $arr[0]->{love},"\n"; print $arr[0]{love},"\n";

    But, indeed the hash still exists in memory as long as something points to it (it isn't let go until its refcount hits 0) --- this is commonly used for constructing a datastructure within a subroutine and returning a reference to it ... think of OO and returning a blessed reference from the constructor for example.

Re: Dissapearing from under one's reference
by mikfire (Deacon) on Mar 28, 2001 at 11:26 UTC
    My first answer is to run it and see. You have the test code.

    For the sake of discussion, no the reference will not disappear. The reference count for %var is incremented once when you declare in the block. When you assign \%var, the reference count gets incremented again. When control exits the block, the reference count is decremented and tested. If it is 0, %var will return to the heap from which it came.

    Quick math says, though, that 1+1-1=1 != 0. %var will not get destroyed and the reference will still be there.

    mikfire