Perl | Scope of Variables
The scope of a variable is the part of the program where the variable is accessible. A scope is also termed as the visibility of the variables in a program. In Perl, we can declare either Global variables or Private variables. Private variables are also known as lexical variables.
Scope of Global Variables
Global variables can be used inside any function or any block created within the program. It is visible in the whole program. Global variables can directly use and are accessible from every part of the program.
Example 1: The variable $name is declared at the beginning of the code. It will be visible till the end of the file everywhere. Even inside blocks. Even if those are in the function declarations. If we change the variable inside the block, that will change the value for the rest of the code. Even outside of the block.
GFG GFG GeeksforGeeks GeeksforGeeks
1 GFG 2 GFG 3 GFG
Scope of Lexical Variables(Private Variables)
Private variables in Perl are defined using my keyword before a variable. my keyword confines variables in a function or block in which it is declared. A block can either be a for loop, while loop or a block of code with curly braces around it. The local variable scope is local, its existence lies between those two curly braces(block of code), outside of that block this variable doesn’t exist. These variables are also known as lexical variables.
Note: When private variables are used within a function or block, then they hide the global variables created with the same name. When we call a subroutine with a private variable, it can be used within that function. As soon as the subroutine exits, the private variables can no longer be used.
1 Global 2 Global Global and Private Variable defined in above block: 3 Hide
In Perl, we have one more type of scoping called Package Scoping. This is used when we need to make variables which can be used exclusively in different namespaces.”main” is the default namespace in every Perl program. Namespaces in Perl are defined using the package keyword.
Value of Var1: Main Namespace Value of var1: Value of var1: Pack1 Namespace Value of var1: Main Namespace Value of var1: Pack1 Namespace
Our Keyword in Perl: “our” keyword only creates an alias to an existing package variable of the same name. our keyword allows to use a package variable without qualifying it with the package name, but only within the lexical scope of the “our” declaration. A variable declared with our keyword declares an alias for a package variable that will be visible across its entire lexical scope, even across package boundaries.
first_name = Shashank second_name =