in reply to Subs: Pass references or return them?

It is ok (and even necessary in many cases) to return a reference. Even though the scope within the sub dies, the variable (or expression) to which you passed the reference is still holding onto the reference, and its data. Perl is smart enough not to destroy the referenced data until all references to it fall out of scope or are reassigned. Think of it this way; the reference inside of the sub fell out of scope, but the data to which it pointed doesn't care about scope as much as it cares about being pointed to by someone, or relevant to someone.

I read where a monk earlier today on this site compared references to cards from a library card catalogue. The card tells where to get the book. Continuing with that analogy, simply make the assumption that the librarian doesn't dispose of a book until all of the library catalogue cards pointing to it have been tossed out first.

Dave

"If I had my life to do over again, I'd be a plumber." -- Albert Einstein

  • Comment on Re: Subs: Pass references or return them?

Replies are listed 'Best First'.
Re: Re: Subs: Pass references or return them?
by knexus (Hermit) on Sep 03, 2003 at 21:03 UTC
    Thanks, that helps and it actually makes sense to me. The analogy is a good one I think.