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.
Now, let’s consider the case when we have the same variable names for global and local variables.
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:
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.