Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: The danger is passing back references to local subroutines.

by thelenm (Vicar)
on Jun 18, 2002 at 19:40 UTC ( [id://175475]=note: print w/replies, xml ) Need Help??


in reply to The danger is passing back references to local subroutines.

Perl variables are reference-counted, and are automatically destroyed when the reference count reaches zero. Since your subroutine is returning a reference to a scalar, that scalar will not automatically be destroyed when the subroutine exits. That's because there's still a reference to it, as long as you store that reference somewhere. If you get rid of that reference (i.e., the variable where you stored the reference goes out of scope or is undefed), then the data will be destroyed.

Update: I forgot to give a helpful reference: perlref and perlobj have some nice information on reference counting if you want to know more.

-- Mike

--
just,my${.02}

Replies are listed 'Best First'.
Re: Re: The danger is passing back references to local subroutines.
by janx (Monk) on Jun 18, 2002 at 20:09 UTC
    There also is a great article by Simon Cozens over at perl.com describing closures.
    You might enjoy that one, too

    Kay

      What he has now is not a closure. It would be a closure if he used his idea of declaring the variable above and referencing it inside the sub.

      UPDATE:
      Actually, as long as he still passes by reference it's not a closure. Here's an example of what would make it a closure:

      my $ref_to_big_chunk; get_big_chunk(8675309); print "And the big data is: "; print $$ref_to_big_chunk; sub get_big_chunk { my $jenny_tel = $_[0]; my $big_jenny = [ all work done here to make this huge ] $ref_to_big_chunk = \$big_jenny; }
      Note that this is a terrible way to do it because it's no longer obvious that the get_big_chunk() sub alters $ref_to_big_chunk.
        I actually just wanted to provide another pointer in an potentially interesting direction.

        That's why I didn't reply to the original question.
        I wouldn't write it that way either.

        Kay

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-04-25 16:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found