Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Scope of variables

  • scope

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.

#!/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

#!/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.