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.
What happens when using my and local with the same variable declared in two different blocks?
Many answer that
localandmywork the same, but that’s not true.localworks only with global variables (package variables). A variable declared withmyis invisible tolocal.
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"
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.