In Perl, variable scoping is a crucial aspect of writing maintainable and bug-free code. Understanding the differences between my
, our
, and local
can help developers manage variable visibility effectively.
my
defines a variable that is scoped to the current block. It cannot be accessed outside its declaring block.
our
, on the other hand, declares a package variable that can be seen across the entire package, allowing for shared state.
Finally, local
temporarily backs up the value of a global variable, allowing the original value to be restored once out of scope.
# Example demonstrating my, our, and local
{
my $local_var = "I'm local"; # scoped to this block
print "$local_var\n";
}
print "$local_var\n"; # This will cause an error, as $local_var is not accessible here.
our $global_var = "I'm global"; # scoped to the package
print "$global_var\n";
sub example {
local $global_var = "I'm temporarily local"; # This will override the global variable
print "$global_var\n"; # Outputs: I'm temporarily local
}
example(); # Calls the function
print "$global_var\n"; # Outputs: I'm global, as the local change has ended in example()
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?