Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^2: Accessing HASH pushed into @array ('strict refs' in use error)

by sbrothy (Initiate)
on Jan 08, 2014 at 14:08 UTC ( #1069800=note: print w/ replies, xml ) Need Help??


in reply to Re: Accessing HASH pushed into @array ('strict refs' in use error)
in thread Accessing HASH pushed into @array ('strict refs' in use error)

Thanks for your input. But I'm not really interested in sending back references to hashes am I? Won't they go out of scope when I enter the next 'for' run?


Comment on Re^2: Accessing HASH pushed into @array ('strict refs' in use error)
Re^3: Accessing HASH pushed into @array ('strict refs' in use error)
by Athanasius (Monsignor) on Jan 08, 2014 at 14:23 UTC

    No! Perl uses reference counting, so an element of storage is eligible for garbage collection only when its reference count falls to zero. When you create the %result variable with my, its reference count is one. When you create a reference to it and push that reference onto @array, the reference count of the memory holding the data is incremented to 2. Then, when the for loop is exited iterates, the lexical variable %hash does indeed go out of scope, so the reference count of the memory it is using is decremented back to 1. But it’s still greater than 0, so the data won’t be garbage collected.

    This is one of the features of Perl that make it a joy to work with. As a general rule, Perl is designed to “do the right thing”, which in this case means keeping the data around as long as it’s needed. Reference counting ensures that the data is still valid and available when it is later accessed via the @array variable.

    But — try it to see!

    Hope that helps,

    Update 1: Improved wording slightly.
    Update 2: Added link.
    Update 3: s/is exited/iterates/.

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Thanks for the clarification. I guess my C / C++ upbringing is clouding my coding here. I hadn't thought of the garbage collecting and the fact that I'm not required to keep track of memory as I use it.
Re^3: Accessing HASH pushed into @array ('strict refs' in use error)
by ikegami (Pope) on Jan 08, 2014 at 14:36 UTC
    Think of my as another language's new: It dynamically creates a variable. (This isn't quite true, but it is the idea behind my, and a good way of thinking of it.)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1069800]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2014-09-20 17:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (160 votes), past polls