Variable Scope Explained: my, our, and local
Scope defines where a variable is accessible inside your program. In Perl, managing scope correctly is crucial for keeping scripts stable and avoiding hard-to-track visual bugs.
1. Lexical Scope: `my`
The my keyword declares a lexically scoped variable. This means the variable only exists within the block of code (defined by curly braces {}) where it is declared.
use strict;
use warnings;
{
my $secret = "Keep out!";
print $secret; # Works fine
}
# print $secret; # CRASHES! $secret no longer exists outside the block above.
Always default to using my. It prevents your variables from bleeding into other areas of your script.
2. Package Scope: `our`
The our keyword declares a package-wide global variable. It allows the variable to be shared across multiple modules or file packages while keeping use strict from throwing a compiler error.
our $global_config = "system_enabled";
3. Dynamic Scope: `local`
This is a unique concept in Perl. local does not create a new variable; instead, it temporarily saves the current value of an existing global (package) variable and restores it when the code block finishes executing.
our $status = "Running";
{
local $status = "Paused";
print "$status\n"; # Outputs: Paused
}
print "$status\n"; # Outputs: Running (the original global state is restored!)