Variable Scope
Let's discuss the scope of variables in Perl.
We'll cover the following
Introduction
The scope of a variable refers to the variable’s visibility, i.e. which part of the program can access that variable.
Types of variables
There are two types of variables depending on the scope (or visibility):
- Local variables
- Global variables
Local variables
Variables defined within the body of a function or subroutine using the my
keyword are called local variables. A local variable cannot be accessed outside of its respective subroutine.
$number = 20; # if my is not used then its scope is globalsub foo{my $num = 10; # using my keyword for local variableprint "Local Variable value" .$num . "\n";}foo(); #Will print 10 because text defined inside function is a local variableprint "global Variable value " . $number . "\n";
Now, let’s consider the case when we have the same variable names for global and local variables.
$number = 20; # if my is not used then its scope is globalsub foo{my $number = 10; # using my keyword for local variableprint "Local Variable value" .$number . "\n";}foo(); #Will print 10 because text defined inside function is a local variableprint "global Variable value " . $number . "\n";
If we remove the keyword my
before our local variable, then it displays “10” as a result for both. Try it if you want to!
Global variables
The variables defined outside the body of the subroutine are called global variables.
A global variable can be accessed in any part of the program.
However, in order to modify a global variable within a subroutine, we need to use the $::
keyword. This is done by placing the $::
keyword in front of the variable.
Below is an example of how we use global variables:
$num1 = 5; # global variables$num2 = 2;sub multiply(){$::num1 = 10;$::num2 = 20;return $num1 * $num2;}# When in the global scope, regular global variables can be used# without explicitly stating '$::variablename'print "num1 is: $num1\n";print "num2 is: $num2\n";print multiply();
The following figure illustrates the difference between global and local variables:
Using variable variables for function calls
We discussed variable variables earlier. Variable variables are useful for mapping function/method calls. Consider the following code snippet, where we use variable variables to call a function sum
which takes two integers and returns their sum.
sub sum {return @_[0] + @_[1];}print sum(2, 4); # outputs 6;