Perl Variable

Perl Variable could be defined in two scope: lexical and package. Lexical variables are like local variables in other languages, that is its lifetime end or get garbage collected when it is out of scope unless it is referenced#. They are defined by my keyword. Package variables are defined in the most recently declared namespace’s scope with the our keyword. It is sort of like a global variable that will live throughout the lifetime of the program. The following shows how to define a package variable:

package MyPackage;
our $variable = "This is my variable";

If the package variable is defined in a lexical scope, and we want access it outside the scope, we need to include the package qualifier in front of it shown as follow:

print $MyPackage::variable;

To avoid hassles on changing package variable causes change in the program state, local() function should be used in order to create a temporary variable for the package variable. The change happened on the temporary variable will not be propagated to the package variable in the global scope, thus it is safe for alteration.

local($MyPackage::variable) = "Now it's temporary variable";
Links to this page
  • Perl Reference

    A referent (referenced #Perl Variable) will not be garbage collected once out of scope. This means that the variable is still alive in the memory but it can’t be accessed via name (variable name). Instead, it should be referred with the corresponding reference name.

#perl