Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 43 ยท Subroutines

Scope, Closures and Recursion

Understand Perl variable scope with my, our, local and state, build closures and counters, write recursive subs, and use dispatch tables.

Scope answers a simple question: where in your program can a variable be seen? Perl's answer has a few layers, and getting them right is the difference between clean code and mysterious bugs. This lesson explains the four declarations you will meet (my, our, local and state), then builds on them with closures, recursion and dispatch tables.

If you already know use strict from use strict and use warnings, you know that every variable should be declared. Here you learn what each declaration actually means.

Perl is not installed on this site, so the Perl code below is read-only, and its output comes from a real Perl 5.42 run. The interactive examples are Python stand-ins that show the same ideas.

Four ways to declare

my Private to the enclosing block.
our A package variable, visible by name.
local Temporarily replaces a global.
state Keeps its value between calls.

Use my by default.

1 / 2

Lexical scope with my

A variable declared with my is lexical: it exists from its declaration to the end of the enclosing block (the nearest pair of curly braces, or the whole file). Inside a block, a new my variable with the same name shadows the outer one, and the outer one returns at the closing brace.

PERL
use v5.36;

my $x = "outer";
{
    my $x = "inner";
    say $x;
}
say $x;
TEXT
inner
outer

Almost every variable you write should be a my variable. Keeping variables in the smallest scope possible means a change in one place cannot break code far away. Loop variables, like the one in for my $i (...), are scoped to their loop automatically.

Package variables with our

A our declaration creates a package variable, which lives in the symbol table under the current package (by default main) and can be reached from anywhere by its full name, such as $main::g. The our keyword also gives you a short lexical alias, so strict mode allows you to use the short name.

PERL
our $g = "global";

sub show { say $g }
show();
TEXT
global

Package variables are shared state, so use them rarely: for configuration constants and for special variables that modules read, like @ISA or $VERSION (you will see these in Packages and Modules).

Temporary changes with local

local does not create a new variable. It saves the current value of a package variable, gives it a temporary value, and restores the old value when the enclosing block ends. During that time, every sub that is called sees the temporary value, because package variables are visible everywhere.

PERL
our $g = "global";
sub show { say $g }

sub test {
    local $g = "localized";
    show();
}

test();
show();
TEXT
localized
global

You will mostly use local on Perl's special variables, for example local $_;, local $/; (to read a whole file at once) or local $| = 1;. For your own variables, prefer my, which is safer because other code cannot see it.

Persistent variables with state

A state variable is private to its block like a my variable, but it is initialized only once and keeps its value between calls. It is the neat way to write a counter:

PERL
use v5.36;

sub counter {
    state $n = 0;
    return ++$n;
}

say counter() for 1..3;
TEXT
1
2
3

state needs use feature 'state', which use v5.10 and later turn on. In the code above use v5.36 already does that. Before state existed, people used a closure for the same purpose, as the next section shows.

Closures

A closure is a subroutine that remembers the my variables that were in scope when it was created. You make one with an anonymous sub (sub { ... }), usually returned from another sub:

PERL
sub make_counter {
    my $count = shift // 0;
    return sub { return ++$count };
}

my $first  = make_counter();
my $second = make_counter(10);

say $first->();     # 1
say $first->();     # 2
say $second->();    # 11
TEXT
1
2
11

Each call to make_counter creates a new $count, and the returned sub keeps it alive after make_counter has finished. The two counters are independent. The arrow ->() calls a code reference; you will study references properly in References.

Closures also capture loop variables correctly in Perl, because every pass of for my $i gets a fresh $i:

PERL
my @subs;
for my $i (1..3) {
    push @subs, sub { $i * 10 };
}
say join ",", map { $_->() } @subs;
TEXT
10,20,30

The Python stand-in below builds the same counter. Python uses nonlocal to say that an inner function should change the outer variable, which Perl does automatically.

Python Stand-in: a closure with private state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Recursion

A recursive sub calls itself. It needs two parts: a base case that stops the recursion, and a step that moves toward it. With signatures, a factorial is only a few lines:

PERL
sub fact ($n) {
    return $n <= 1 ? 1 : $n * fact($n - 1);
}
say fact(5);

sub fib ($n) {
    return $n < 2 ? $n : fib($n - 1) + fib($n - 2);
}
say join ",", map { fib($_) } 0..10;
TEXT
120
0,1,1,2,3,5,8,13,21,34,55

Recursion is a natural fit for tree-shaped data. This sub prints a nested hash, indenting each level one step more (hash references are covered in References):

PERL
sub walk ($data, $depth = 0) {
    for my $key (sort keys %$data) {
        say "  " x $depth, $key;
        walk($data->{$key}, $depth + 1) if ref $data->{$key};
    }
}

walk({ a => { b => {}, c => 1 }, d => 2 });
TEXT
a
  b
  c
d

Perl warns "Deep recursion on subroutine" when a sub calls itself more than 100 levels deep. It is only a warning: the program keeps running, but a loop is often a safer choice for very deep or very long work. Also beware that the naive fib above does a lot of repeated work, so it is slow for large numbers.

Callbacks and dispatch tables

Because a sub can be stored in a variable, you can pass it around like any value. A callback is a sub you hand to another sub to call later. Perl's map, grep and sort blocks are built-in examples.

A dispatch table is a hash whose values are subs. It replaces long if/elsif chains, and it is the usual Perl answer to "switch":

PERL
my %ops = (
    add => sub ($a, $b) { $a + $b },
    mul => sub ($a, $b) { $a * $b },
);

for my $name (sort keys %ops) {
    say "$name: ", $ops{$name}->(3, 4);
}

say "unknown operation" unless exists $ops{div};
TEXT
add: 7
mul: 12
unknown operation

Adding a new operation means adding one line to the hash, and checking exists first guards against unknown names. See Hashes for exists.

Here is a dispatch table and a recursive function in Python:

Python Stand-in: a dispatch table and recursion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the scope of a variable declared with my inside a block?

    my creates a lexical variable that exists until the closing brace of its block.
  2. 2. What does local $g = 5; do?

    local saves the old value of a package variable and restores it when the block ends. It does not create a new variable.
  3. 3. Which declaration keeps its value between calls to a sub?

    A state variable is initialized once and persists across calls, while staying private to its block.
  4. 4. Why are two counters from make_counter() independent?

    Each call runs the my declaration again, producing a fresh variable captured by the returned sub.
  5. 5. What is a dispatch table?

    A dispatch table maps names to subs, so you look up and call the right action by key.

Summary

  • my makes a lexical variable limited to its block; use it by default.
  • our names a package variable, and local temporarily replaces a package variable, restoring it at the end of the block.
  • state creates a private variable that keeps its value between calls.
  • A closure is an anonymous sub that remembers the lexical variables in scope when it was created.
  • Recursion needs a base case, and dispatch tables (hashes of subs) replace long if/elsif chains.

Next, start pattern matching with Regular Expressions Basics.