> Forgive me for my dense question, but how do you return
> a reference of a hash if the hash is private to the
> subroutine? Can that be done?
Don't think of the hash as "private" to the subroutine; yes, it's
declared lexically within the sub, but that's not all that matters.
Think of the hash as a piece of data *somewhere* that you've
referenced lexically within the sub.
Perl's garbage collection is based on reference counting; so each
reference to such a piece of data increments the reference count.
Once you've declared
my $hash = {}
the
reference count of the underlying structure is incremented to
one.
Normally, you'd just have that one reference to the data, so once
the lexical has gone out of scope--at the end of the subroutine--the
data would be destroyed. But not here, because you've returned
a reference to the data and assigned it somewhere else. Even though
leaving the sub decrements the reference count, then, you
re-increment it by assigning the return value of the sub. So the
reference count is still one, and the data is still there, and valid.
The data won't be destroyed until all references to it have gone
away.
BTW: this is, as far as I know, correct, but someone who knows
more about Perl's internals is free to correct anything wrong. :) |