laziness, impatience, and hubris | |
PerlMonks |
Re: What's a reference? What's a variable? What's scope?by Juerd (Abbot) |
on Dec 28, 2002 at 19:36 UTC ( [id://222774]=note: print w/replies, xml ) | Need Help?? |
Perl uses a garbage collector. The technique for collecting garbage that Perl uses is called 'reference counting'. Every variable in Perl has a counter, the reference count. When the variable is created, the counter is set to 1. When the variable is referenced, it is increased by one.
Line 3: $foo is created, its reference count is now 1. Line 4: $foo is used for print, its reference count is increased. The reference count is now 2. Line 4: When print returns, the reference count is decreased. The reference count is now 1 again. Line 5: $foo's scope ends, the reference count is decreased. Because the reference count is 0 now, the variable is destroyed. Line 6: There is no $foo in this scope, and because the $foo in the block's scope no longer exists, there is no way to access it.
Line 4: $foo is created, its reference count is now 1. Line 5: $foo is used for print, its reference count is increased. The reference count is now 2. Line 5: When print returns, the reference count is decreased. The reference count is now 1 again. Line 6: $bar is assigned a refence to $foo. $foo's reference count is now increased, and has a new value of 2. Line 7: $foo's scope ends, the reference count is decreased. Because the reference count is 1 (not 0, as in the previous example) now, the variable is not destroyed. Line 8: There is no $foo in this scope, but the variable that was called $foo in the block's scope can still be accessed through $bar. An extra $ is used to dereference it. Further reading:
Additional nitpicking:
In Section
Seekers of Perl Wisdom
|
|