Home > Perl > Object Oriented Programming > Perl Packages - Part 2 (Variable Scoping)
Perl Packages - Part 2 (Variable Scoping)
Written by Philip L Yuson   
What is in this article
The article discusses about the different ways of scoping your variables. Scoping defines the visibility of a variable. Introduction
Before we talk about scoping, we will first discuss about blocks of code. A block is simply a set of statements between matching curly brackets {}. Subroutines, conditional statements, loop statements, eval statements do and files used within a script contain blocks. 


sub myFunction {
print "This is a function";
if (@_) {
print "$_ ";
The my Function
Variables defined using the my function are visible only within the block and its subordinate blocks. So if you have something like this:
package myPackage;
my $var = "main variable";
print "main: $var ";
my $var = "second var";
print "Second: $var ";
print "Before Exit: $var ";

The result will be:

main: main variable
Second: second var
Before Exit: main variable

The first my $var defines the $var variable for the myPackage package. The second my $var defines the $var variable within the block. This variable is totally different from the one defined before it. Once the execution goes out of the block, the $var variable in the block is released. This is the reason why on the last print statement, the variable printed is the one defined on top rather than the one defined within the block.

Why do you want to do this
This comes in handy in object oriented programming. Remember that in the previous article, we can reference a variable in another package by specifying the package name as a prefix (example: $street::name). When a variable is defined using the my function, the visibility of the variable is limited only to within the block - or package as the case may be.

Copyright: © 2018 Philip Yuson