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.
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.
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.
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.
# 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
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?