What is the difference between 'my' and 'our' keywords in Perl?
In the Perl programming language, my and our are keywords used for variable declaration, but they have different scoping rules.
The my keyword
A lexical variable is declared by using the my keyword. A lexical variable is a variable that can only be accessed within the block of code that it is contained within, such as a loop or subroutine. Once the block of code is exited, the variable goes out of scope and cannot be accessed anymore. Variables with the same name in multiple scopes are distinct because each variable instance declared with the my prefix is limited to its scope.
Code
The coding example below demonstrates the use of the my keyword:
sub mySub {my $x = 25; # $x is a lexical variable, accessible only within this subroutineprint "Inside the mySub subroutine: x = $x\n";}mySub();print "Outside the subroutine: x = $x\n"; # $x is not accessible here
Code explanation
- Lines 1–4: The code defines a Perl subroutine named
mySubwith a lexical variable$x.$xis accessible only within themySubsubroutine and holds the value25. - Line 6: When
mySubis called, it prints the value of$x. - Line 7: The attempt to print the value of
$xoutside the subroutine will not return any value since lexical variables are limited to their respective scopes.
The our keyword
A package (global) variable is declared with the our keyword. A package variable is accessible throughout the entire package it is declared in. In contrast to lexical variables, package variables are not constrained to a single scope and maintain their value over several blocks of code that are part of the same package.
Code
The coding example below demonstrates the use of the our keyword:
our $y = 20; # $y is a package (global) variable, accessible within the packagesub print_global_variable {print "Inside the package: y = $y\n";}sub modify_global_variable {$y += 5;}print_global_variable();modify_global_variable();print_global_variable();
Code explanation
-
Line 1: We define a global variable
$yusing theourkeyword, making it accessible throughout the package. -
Lines 3–9: We create
print_global_variableandmodify_global_variablesubroutines to print and modify the global variable$y. -
Lines 11–12: We call the
print_global_variablesubroutine, which prints the initial value of$y, and then call themodify_global_variablesubroutine, which increases the value of$yby5. -
Line 13: Finally,
print_global_variableis called again, displaying the updated value of$y(25) since modifications to the global variable are reflected across all parts of the package.
Conclusion
The my keyword is used to define lexical variables with a specific scope within a block of code (often a subroutine or a loop), but the our keyword is used to define package variables with a broader scope, accessible across several blocks within the same package.
Free Resources