ZetCode

Perl local vs my

last modified November 25, 2026 Perl 5.44

Perl has two keywords that look alike but do very different things. my creates a new lexical variable that exists only in the enclosing block and is visible only to the code written inside that block. local creates no variable at all: it saves the current value of an existing global variable, gives it a temporary value, and puts the old value back when the enclosing block exits.

The difference is the difference between lexical and dynamic scope. A my variable is visible where the code is written. A local value is visible to everything that runs while the block is active, including subroutines called from it. The Perl scope article introduces both kinds of scope; this article looks at local in depth and shows when to reach for it instead of my.

my and local side by side

The first program declares a package variable with our and changes it in two subroutines, once with my and once with local. Both subroutines then call the same function, which reads the variable.

my_local.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

our $name = 'Paul';

sub greet {
    say "Hello there, $name";
}

sub with_my {
    my $name = 'Lucy';
    greet();
}

sub with_local {
    local $name = 'Lucy';
    greet();
}

with_my();
with_local();
greet();

In with_my, the my $name declaration creates a new lexical variable that hides the package variable only inside with_my. The greet function is written outside that block, so it still sees the package variable and prints Paul.

In with_local, there is only one $name: the package variable. local gives it the value Lucy for as long as with_local runs, so greet prints Lucy. After the subroutine returns, the original value is back, and the last call prints Paul again.

$ perl my_local.pl
Hello there, Paul
Hello there, Lucy
Hello there, Paul

Restoring values when a block exits

A local value lasts until the end of the enclosing block, not only until the end of a subroutine. Nested blocks stack their saved values, and each block exit restores exactly one of them.

nested.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

our $level = 0;

sub show {
    say "level $level";
}

show();

{
    local $level = 1;
    show();

    {
        local $level = 2;
        show();
    }

    show();
}

show();

Each bare block saves the value that is current when it starts and restores it when it ends. The inner block saves 1 and sets 2; when it closes, the value goes back to 1, and the outer block later restores 0. The show function never receives the level as an argument; it reads whatever value is in effect at the moment it is called.

$ perl nested.pl
level 0
level 1
level 2
level 1
level 0

Restoring values after die

A hand-written save and restore with a temporary my variable looks like it does the same job as local. It does not: when the code between the save and the restore dies, the restore never runs.

restore_die.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

our $mode = 'normal';

sub manual {
    my $saved = $mode;
    $mode = 'maintenance';
    die "disk full\n";
    $mode = $saved;
}

sub with_local {
    local $mode = 'maintenance';
    die "disk full\n";
}

eval { with_local(); 1 } or print "error: $@";
say "after with_local: $mode";

eval { manual(); 1 } or print "error: $@";
say "after manual: $mode";

Both subroutines switch $mode to maintenance and then die. The restore line in manual is never reached, so the global variable stays in maintenance mode after the error is caught. The value set with local is restored as part of leaving the block, which also happens when an exception unwinds the stack. That makes local the safe way to change a global temporarily. Catching errors with eval is covered in Perl error handling.

$ perl restore_die.pl
error: disk full
after with_local: normal
error: disk full
after manual: maintenance

Changing special variables safely

Most uses of local in practice involve Perl's special variables, which are all globals. A subroutine that changes one of them without local changes it for the whole program.

leak.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

sub row_leaky {
    $, = ',';
    print @_;
    print "\n";
}

sub row {
    local $, = ',';
    print @_;
    print "\n";
}

row(qw(id name age));
print qw(x y z), "\n";

row_leaky(qw(id name age));
print qw(x y z), "\n";

The $, variable is the output field separator, the string that print puts between its arguments. The row function localizes it, so the following print joins its arguments with nothing as usual. The row_leaky function assigns to it directly, and the change outlives the call: the last print puts commas between all its arguments, including one before the newline.

$ perl leak.pl
id,name,age
xyz
id,name,age
x,y,z,

Protecting $_ in a subroutine

The default variable $_ is a global too. Inside a for loop without a loop variable, $_ is an alias of the current array element, so a subroutine that assigns to $_ writes straight into the caller's array.

local_topic.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

sub shout_bad {
    $_ = uc shift;
    return "$_!";
}

sub shout {
    local $_ = uc shift;
    return "$_!";
}

my @birds = qw(falcon owl eagle);

for (@birds) {
    print shout($_), ' ';
}
say "| @birds";

for (@birds) {
    print shout_bad($_), ' ';
}
say "| @birds";

Both subroutines store an uppercased copy of the argument in $_ and return it with an exclamation mark. The printed results are the same, but shout_bad overwrites each element of @birds, because its $_ is the loop's alias. local $_ gives shout its own temporary $_ and leaves the caller's data alone. Any subroutine that uses $_ for its own work should localize it first, or better, use a my variable instead.

$ perl local_topic.pl
FALCON! OWL! EAGLE! | falcon owl eagle
FALCON! OWL! EAGLE! | FALCON OWL EAGLE

Localizing hash and array elements

local can change a single element of a hash or an array and leave the rest alone. Unlike plain local, this also works on elements of my hashes and arrays. The delete local form removes an element temporarily.

elements.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my %opts = (color => 'auto', width => 80);
my @path = qw(/usr/bin /bin);

sub show {
    my $color = exists $opts{color} ? $opts{color} : '(none)';
    say "width=$opts{width} color=$color path=@path";
}

sub narrow {
    local $opts{width} = 40;
    local $path[0] = '/opt/bin';
    show();
}

sub plain {
    delete local $opts{color};
    show();
}

narrow();
plain();
show();

narrow changes one hash value and one array element for the duration of the call. plain uses delete local, so the color key does not exist while show runs, which is different from setting it to undef. After both calls, the final show sees the original data. Localizing an element is a convenient way to override one configuration setting for a single operation.

$ perl elements.pl
width=40 color=auto path=/opt/bin /bin
width=80 color=(none) path=/usr/bin /bin
width=80 color=auto path=/usr/bin /bin

Localizing a whole array

local also works on a whole package array or hash. Without an assigned value, the localized array starts out empty; with one, it holds the new list until the block exits.

whole_array.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

our @queue = qw(mail backup report);

sub drain {
    my @done;

    while (my $job = shift @queue) {
        push @done, $job;
    }

    say "ran: @done";
}

sub urgent {
    local @queue = qw(alert);
    drain();
}

urgent();
say "queue: @queue";

drain();
say "queue: @queue";

The drain function processes and empties the global job queue. urgent gives it a temporary queue with one job, so the regular jobs are untouched when urgent returns. The second drain call works on the real queue and empties it for good. The same technique is behind the idiom local @ARGV = ($file), which lets the <> operator read a chosen file for the duration of a block.

$ perl whole_array.pl
ran: alert
queue: mail backup report
ran: mail backup report
queue: 

Tracking recursion depth

Because each call saves and restores its own value, local suits values that follow the call chain, such as the current nesting depth of a recursive function.

depth.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

our $depth = 0;

sub trace {
    say '  ' x $depth, @_;
}

sub fact {
    my $n = shift;

    trace("fact($n)");
    local $depth = $depth + 1;

    return 1 if $n <= 1;

    my $res = $n * fact($n - 1);
    trace("= $res");

    return $res;
}

my $val = fact(4);
say "result: $val, depth: $depth";

Each call of fact prints a trace line and then raises $depth by one with local. The trace function indents its output by the current depth without receiving it as an argument. When a call returns, its increment is undone, so the result lines line up with the calls that produced them and the depth is back to zero at the end. Passing the depth as an extra argument would work too, but it would have to be threaded through every function on the way down.

$ perl depth.pl
fact(4)
  fact(3)
    fact(2)
      fact(1)
      = 2
    = 6
  = 24
result: 24, depth: 0

local values and closures

An anonymous subroutine captures the my variables it uses, but not the local values in effect when it was created. It reads a package variable when it runs.

closure.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

our $unit = 'cm';
my $describe;

{
    local $unit = 'mm';
    my $label = 'height';

    $describe = sub { "$label in $unit" };
    say 'inside:  ', $describe->();
}

say 'outside: ', $describe->();

The closure captures the lexical $label, which keeps its value after the block ends. The $unit variable is global, so the closure reads whatever value it has at call time: mm inside the block and cm outside, after local has restored it. Closures are covered in Perl closures.

$ perl closure.pl
inside:  height in mm
outside: height in cm

local works only on globals

A my variable lives in a lexical pad, not in the package symbol table, so it has no global value that local could save and restore. Applying local to it is a compile-time error.

local_my.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $count = 1;

sub bump {
    local $count = 2;
    return $count;
}

say bump();

Perl refuses to compile the program and reports the line of the local. To change a lexical variable temporarily, declare a new my variable in an inner block instead; to override a value for the subroutines called from a block, make it a package variable with our.

$ perl local_my.pl
Can't localize lexical variable $count at local_my.pl line 9.

Best practices

The following guidelines help to choose between the two keywords.

Source

perlsub: Temporary values via local() · perlsub: Private variables via my() · perlfunc: local

In this article we have compared local with my, restored global values on block exit and after die, protected special variables and $_, localized single elements and whole arrays, and seen how local values interact with closures. The special variables that are most often localized are described in Perl special variables.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Perl tutorials.