TExcelTAD
Home › Perl › Scope: my, our, local

Scope: my, our, local

Scope decides where a variable name is visible. Perl has three declarations that sound similar but do very different things:

Declaration Kind of variable Visible in Typical use
my lexical the enclosing block or file, from the declaration onward almost everything
our package (global) a lexical alias to a package variable module settings, @ISA, $VERSION
local (not a declaration) temporarily replaces a global value until the block ends special variables like $/, $,

my: lexical scope

A my variable exists from its declaration to the end of the enclosing block ({ ... }), or the end of the file. Inner blocks can see outer variables, and may declare their own variable with the same name, which shadows the outer one:

perl · try it yourself
use strict;
use warnings;

my $level = "file";

{
    my $level = "block";          # shadows the outer $level
    my $only_here = 42;
    print "Inside: $level, $only_here\n";
}

print "Outside: $level\n";

for my $i (1 .. 2) {
    my $square = $i * $i;         # a fresh $square on every iteration
    print "i=$i square=$square\n";
}
Inside: block, 42
Outside: file
i=1 square=1
i=2 square=4

Using $only_here or $square after their blocks would be a compile error under strict. Keeping variables in the smallest possible scope makes programs easier to understand.

Tip: use warnings reports "my" variable $x masks earlier declaration in same scope if you accidentally declare the same name twice in one block.

state: variables that persist

A state variable (enabled by use feature 'state') is lexical like my, but it is initialised only once and keeps its value between calls of the sub:

perl · try it yourself
use strict;
use warnings;
use feature 'state';

sub next_ticket {
    state $number = 100;
    return ++$number;
}

print "Ticket ", next_ticket(), "\n" for 1 .. 3;
Ticket 101
Ticket 102
Ticket 103

our: package variables

Package (global) variables belong to a package (namespace), such as main or My::Module. Their full name includes the package: $main::debug, $Config::verbose. our declares a short lexical name for a package variable, which keeps strict happy:

perl · try it yourself
use strict;
use warnings;

package Settings;
our $verbose = 1;
our @servers = qw(alpha beta);

package main;

print "Verbose: $Settings::verbose\n";
print "Servers: @Settings::servers\n";

our $count = 5;                   # this is $main::count
print "Through the full name: $main::count\n";
Verbose: 1
Servers: alpha beta
Through the full name: 5

Package variables are visible from anywhere through their full name, which is exactly why you should use them sparingly.

local: temporary values for globals

local saves the current value of a global variable, gives it a new value, and automatically restores the old value when the enclosing block ends, even if the block is left by an error. The new value is seen by every sub called from within the block ("dynamic scope"):

perl · try it yourself
use strict;
use warnings;

our $indent = "";

sub show { print "${indent}$_[0]\n" }

sub section {
    my ($title, @items) = @_;
    show($title);
    local $indent = "$indent    ";    # restored when section() returns
    show($_) for @items;
}

section("Fruit", "apple", "pear");
show("back at the top level");
Fruit
    apple
    pear
back at the top level

The most common real use of local is changing one of Perl's special variables for a short while:

perl · try it yourself
use strict;
use warnings;

my @parts = ("a", "b", "c");
{
    local $, = "-";     # output field separator for print
    local $\ = "!\n";   # output record separator
    print @parts;
}
print @parts, "\n";

{
    local 
quot; = ", "; # separator used when interpolating arrays print "List: @parts\n"; } print "List: @parts\n";
a-b-c!
abc
List: a, b, c
List: a b c

Note: local does not create a new variable, and it cannot be used with my variables. If you are not changing a global or special variable, you want my.

Test yourself

Which declaration should you use for ordinary variables?

  1. our
  2. local
  3. my
  4. none, declarations are optional

What does local $/; do?

  1. Declares a new lexical variable
  2. Temporarily sets the global $/ to undef until the block ends
  3. Deletes $/ permanently
  4. Makes $/ read-only

How is a state variable different from my inside a sub?

  1. It is global
  2. It is initialised once and keeps its value between calls
  3. It cannot be changed
  4. It is visible to other subs