In the Perl programming language, my
and our
are keywords used for variable declaration, but they have different scoping rules.
my
keywordA 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.
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
mySub
with a lexical variable $x
. $x
is accessible only within the mySub
subroutine and holds the value 25
.mySub
is called, it prints the value of $x
.$x
outside the subroutine will not return any value since lexical variables are limited to their respective scopes.our
keywordA 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.
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();
Line 1: We define a global variable $y
using the our
keyword, making it accessible throughout the package.
Lines 3–9: We create print_global_variable
and modify_global_variable
subroutines to print and modify the global variable $y
.
Lines 11–12: We call the print_global_variable
subroutine, which prints the initial value of $y
, and then call the modify_global_variable
subroutine, which increases the value of $y
by 5
.
Line 13: Finally, print_global_variable
is called again, displaying the updated value of $y
(25
) since modifications to the global variable are reflected across all parts of the package.
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