What is my vs our vs local in Perl?

In Perl, variable scoping is an important concept that determines the visibility and lifespan of variables. Understanding the differences between my, our, and local is essential for writing efficient and maintainable code.

my

The my keyword is used to declare variables with a lexical scope. This means that the variable exists only within the block of code in which it is declared. It is not accessible outside of that block, making it a good choice for variables that should not interfere with other variables of the same name.

our

The our keyword declares variables with a package scope. This means that the variable is accessible from anywhere within the package in which it is declared. It is commonly used for global variables that need to be shared across multiple subroutines or files.

local

The local keyword temporarily backs up the value of a global variable and allows you to modify it within a specific block or scope. When the scope ends, the variable reverts to its original value. This is useful for temporarily changing the behavior of a global variable without affecting its original state.

Examples

# Example using my sub my_example { my $x = 10; # x is scoped only within my_example print $x; } # Example using our our $y = 20; # y is a global variable sub our_example { print $y; # we can access y here } # Example using local my $z = 30; # z is defined in the outer scope sub local_example { local $z = 40; # temporarily change z print $z; # prints 40 } print $z; # prints 30 again, as local change is gone

Keywords: my our local Perl variable scoping programming