in reply to a general question on references...
Variables like %hash don't contain the data they represent. They point to it. So you are correct that %hash goes out of scope at the end of the sub, but the data that it points to is still there (in this example). Here's a simplified explanation as to why:
Every time something references data contained in a variable, the reference count for the data is increased by one (it should be noted that the hash and the data that it contains maintain separate reference counts, so a hash could go out of scope but some of the data still remain). When the hash is created, it is assigned a reference count of one. When you return the reference to the hash and assign it to $hash_ref, its reference count increases by one, to two. When %hash goes out of scope, the reference count is decreased by one, to one. Since it still has a reference count of one, the data is still there.
Only when $hash_ref goes out of scope (in the example above), will the reference count for the original hash drop to zero, leading Perl to remove all references to it (the data is not actually deleted, as this justs wastes time. It's merely inaccessible).
Cheers,
Ovid
Vote for paco!
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
|
|---|