ProgrammingSenior Perl Developer

Tell us about the peculiarities of variable scope in Perl. What nuances are there with the my and local operators?

Pass interviews with Hintsage AI assistant

Answer

In Perl, variable scope is defined by the keywords my and local.

  • my creates a variable with lexical scope (it works only in the current block).
  • local temporarily saves the current value of a global variable and sets a new one for the duration of the block — it is often used only with global variables (e.g., $_, $/ etc.).

Example:

my $x = 42; # visible only in the current block { local $/ = undef; my $input = <STDIN>; # $/ here is undef, after the block it restores the value }

Using my is preferable due to its more predictable scope.

Trick Question

What happens when using my and local with the same variable declared in two different blocks?

Many answer that local and my work the same, but that’s not true. local works only with global variables (package variables). A variable declared with my is invisible to local.

Example:

our $foo = "global"; { local $foo = "local"; print $foo; # "local" } print $foo; # "global" { my $foo = "lexical"; } # $foo outside the block is the global version, not "lexical"

Examples of real errors due to ignorance of the nuances


Story

In the script, local was used to temporarily replace a variable declared with my, which resulted in no output and caused bugs in event handling in one of the internal modules.


Story

In the project, $_ was “localized” through local inside foreach, expecting to replace $_ for iterators, forgetting that foreach already sets a new $_. The result — a non-working filter and incorrect iteration logic.


Story

The package global variable was not declared with our, and an attempt to localize via local $var led to the script crashing due to strict and warning, and debugging took a day.