How does my vs our vs local affect performance or memory usage?

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.

Variable Declaration

These keywords are used to declare variables with different scopes:

  • my: Creates a new lexical variable that is scoped to the block in which it is defined. It is not accessible outside of that block.
  • our: Declares a package variable that is accessible across the entire package. This is useful for global variables.
  • local: Temporarily backs up a global variable and provides it with a new value within the current block. Once the block is exited, the original value is restored.

Performance and Memory Usage

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.

Example

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"

Perl my our local variable scope performance memory usage lexical variables package variables