4.2 What if That Was the Name?
Typically, all references to a variable
are removed before the variable itself. But what if one of the
references outlives the variable name? For example, consider this
code:
my $ref;
{
my @skipper = qw(blue_shirt hat jacket preserver sunscreen);
$ref = \@skipper;
print "$ref->[2]\n"; # prints jacket\n
}
print "$ref->[2]\n"; # still prints jacket\n
Immediately after the @skipper array is declared,
you have one reference to the five-element list. After
$ref is initialized, you'll have
two, down to the end of the block. When the block ends, the
@skipper name disappears. However, this was only
one of the two ways to access the data! Thus, the five-element list
is not removed from memory, and $ref is still
pointing to that data.
At this
point, the five-element list is contained within an
anonymous array, which is a fancy term for an
array without a name.
Until the value of $ref
is changed, or $ref itself disappears, you can
still continue to use all the dereferencing strategies you used prior
to when the name of the array disappeared. In fact,
it's still a fully functional array that you can
shrink or grow just as you do any other Perl array:
push @$ref, "sextant"; # add a new provision
print "$ref->[-1]\n"; # prints sextant\n
You can even increase the reference count at this point:
my $copy_of_ref = $ref;
or equivalently:
my $copy_of_ref = \@$ref;
The data remains alive until the last
reference is destroyed:
$ref = undef; # not yet...
$copy_of_ref = undef; # poof!
|