Документация
HTML CSS PHP PERL другое

Section 5.2.  What If That Was the Name?

 
Previous
Table of Contents
Next

5.2. What If That Was the Name?

Typically, all references to a variable are gone 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 we declare the @skipper array, we have one reference to the five-element list. After $ref is initialized, we'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 still in memory, and $ref still points to that data.

At this point, the five-element list is in an anonymous array, which is a fancy term for an array without a name.

Until the value of $ref changes, or $ref itself disappears, we can still use all the dereferencing strategies we used prior to when the name of the array disappeared. In fact, it's still a fully functional array that we can shrink or grow just as we do any other Perl array:

push @$ref, 'sextant'; # add a new provision
print "$ref->[-1]\n"; # prints sextant\n

We can even increase the reference count at this point:

my $copy_of_ref = $ref;

or equivalently:

my $copy_of_ref = \@$ref;

The data stays alive until we destroy the last reference:

$ref = undef; # not yet...
$copy_of_ref = undef; # poof!


Previous
Table of Contents
Next
© 2000- NIV