In Perl, the keywords my
, our
, and local
are used for variable declaration and scoping, which can have implications on performance and memory usage. Understanding how these keywords work can help you write more efficient Perl code.
These keywords are used to declare variables with different scopes:
Using my
is generally preferred for performance because it allocates memory only for the duration of its scope. In contrast, our
variables persist for the life of the package, potentially using more memory. Meanwhile, local
could incur overhead due to copying and restoring variable values during its use, though it is still efficient for managing temporary changes to global variables.
my $lexical_var = "I'm local to this block";
our $package_var = "I'm accessible throughout the package";
sub example {
local $package_var = "I'm temporarily changed inside this function";
print "$package_var\n"; // Prints "I'm temporarily changed inside this function"
}
example();
print "$package_var\n"; // Prints "I'm accessible throughout the package"
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?