- scope
Scope of variables
Let's see an example where we create an array and a reference
to it in some arbitrary {} scope. The array is defined within
the scope while the variable holding the reference is defined
outside the scope.
examples/references/scope_of_variables.pl
#!/usr/bin/env perl use strict; use warnings; my $names_ref; { my @names = qw(Foo Bar); $names_ref = \@names; } print "$names_ref->[0]\n"; # Foo # print "@names\n"; # Global symbol "@names" requires explicit package name
examples/references/reference_counting.pl
#!/usr/bin/env perl use strict; use warnings; use Devel::Refcount qw(refcount); my $names_ref; { my @names = qw(Foo Bar); $names_ref = \@names; } print "$names_ref->[0]\n"; # Foo print(refcount($names_ref), "\n"); # 1
After the closing } @names went out of scope already
but $names_ref still lets us access the values.
As $names_ref still holds the reference to the location of the original array in the memory perl keeps the content of the array intact.