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.
use strict; # 1
{ # 2
my $foo = "Hello, world!\n"; # 3
print $foo; # 4
} # 5
print $foo; # 6
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.
use strict; # 1
my $bar; # 2
{ # 3
my $foo = "Hello, world!\n"; # 4
print $foo; # 5
$bar = \$foo; # 6
} # 7
print $$bar; # 8
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:
-
Don't use an & when calling a subroutine. If you do so without using parens, the current @_ is implicitly passed.
-
There's no need to exit() explicitly. If you want to make clear that no code follows, put your subs first (which has more advantages:
your $hash_ref and %hash are shared throughout the program in the current situation - is that really what you want?)
- Yes, I reinvent wheels.
- Spam: Visit eurotraQ.