Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re: my and scope

by McA (Priest)
on Mar 28, 2013 at 21:05 UTC ( #1026040=note: print w/replies, xml ) Need Help??

in reply to my, scope, and references


I try to explain in my own words: In the function you declare and instatiate an array @test_array. You now have one reference on a - lets call it - perl array object. Would you have done nothing with this array, than the last variable @test_array would have gone out of scope, the reference counter on that object would drop to zero and garbage collection would free the space needed for that array object. As soon as you return a reference to that object you increased the reference counter by one. The variable @test_array goes out of scope, but a single reference is still there, which points to an object that was created in the function.

Here an example in C:

char* myfunc() { char* stringpointer; stringpointer = (char*) malloc(5000); if(stringpointer == NULL) { exit(1); } strcpy(stringpointer, "Hallo"); return(stringpointer); }
You create space for an object with malloc and the variable stringpointer does have a reference on it. Then you return the address of stringpointer. The variable stringpointer itself will be removed from stack. But in the calling function you will have a reference on the object.

To be precise: You have to differentiate between scope (what is seen where) and object instantiation and destruction. They can have the same boundaries but they need not to.


Replies are listed 'Best First'.
Re^2: my and scope
by chayashida (Acolyte) on Mar 28, 2013 at 21:25 UTC

    Hi McA,

    I think you explained it perfectly. The last sentence is exactly what was confusing me, and the C example helped immensely.

    Thank you.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1026040]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2018-06-21 10:54 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (118 votes). Check out past polls.