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

I hope this is not a faq, I have SuperSearched for the answer but to no avail.

If I declare a variable to have block scope and then pass a reference to that variable out of the block is that will the local variable (and so the reference) be trashed? I am _really_ spending too much time writting C++ these days. I am getting my mind into a mess over this could someone clear this up for me and explain simply how perl handles scoping in this context.

What I am actually trying to do is create an array of arrays or in truth an array of array references.

Thanks for your help and sorry if this is as dumb a question as it sounds to me, but I really cant get my head around it today.
--

Zigster

  • Comment on Question regarding perl memory management

Replies are listed 'Best First'.
Re: Question regarding perl memory management
by mirod (Canon) on Feb 05, 2001 at 19:06 UTC

    It is sort of a FAQ but it might be hard to find if you really don't know anything about how Perl handles memory management.

    Look at garbage collection guts and Acky Memory, then try a Super Search on reference count and have a look at the first to results.

    In short, no your variable will not disappear as long as at least one reference to it is still in scope.

    Perl conts the references to a value in memory and only releases it when that count goes down to 0. The initial variable gives it a reference count of 1, then the reference to the variable increases it to 2. When the initial variable goes out of scope then the refcount goes back to 1, and only if the reference goes out of scope (or is re-assigned) does the refcount reach 0 and the memory is released.

    Don't worry Zigster, this is friendly Perl and not !@#$%^&* C++ we're talking about.

Re: Question regarding perl memory management
by arhuman (Vicar) on Feb 05, 2001 at 19:19 UTC
    AFAIK and if I understand your question, the memory allocated to this variable won't be 'trashed' if there remains reference of any kind to this memory block.
    I mean as long as you got a reference to a variable (whatever the type hash,array,scalar) you will be able to access it via this reference...
    my $ref; { my $foo=10; $ref=\$foo; print "foo=$foo\n"; print "ref=$ref ($$ref)\n"; } print "foo=$foo\n"; print "ref=$ref ($$ref)\n";

    will produce:
    foo=10 ref=SCALAR(0x80f14ec) (10) foo= ref=SCALAR(0x80f14ec) (10)