Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
Just another Perl shrine
 
PerlMonks  

Can I safely return a reference from a subroutine?

by Kozz (Friar)
on Jun 21, 2000 at 02:09 UTC ( #19121=perlquestion: print w/ replies, xml ) Need Help??
Kozz has asked for the wisdom of the Perl Monks concerning the following question:

I've become very used to putting nearly all my code in subroutines, based on the principal that "If you use the code more than once, it belongs in a subroutine." However, now I am for the first time reading about how passing & returning large values to/from subroutines can be 'computationally expensive'. The solution suggests that it's better to pass & return references instead. But if a scalar/array/hash is created in the subroutine, I have no choice but to return that item itself, rather than a reference since (assuming the variable is created with 'my') the variable will be destroyed upon exiting the subroutine. Is this correct?

In addition, is it always better to use references whenever possible to reduce CPU use if there's a possibility that the values returned could be large?

Comment on Can I safely return a reference from a subroutine?
Re: Can I safely return a reference from a subroutine?
by btrott (Parson) on Jun 21, 2000 at 02:13 UTC

    No, that's not correct. If you pass back a reference, the original data structure won't be destroyed, even though you've left the subroutine.

    This is because of the way Perl's garbage collection is implemented: it uses reference counting, which means that as long as there's a reference to a particular piece of data, that data won't be destroyed. Once the reference count drops to 0, the original data will be garbage collected.

    When you return a reference, the original reference to the data (the one created in the sub) goes away, but you grab a new reference to the data. So the reference count doesn't fall to 0, so the data isn't destroyed until your new reference goes away.

    Does this make sense? Look in perlref for more details on references.

Re: Can I safely return a reference from a subroutine?
by stewbasic (Initiate) on Feb 10, 2011 at 03:29 UTC
    (EDIT) Oops, turns out my comment was wrong.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2014-04-21 05:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (490 votes), past polls