Perl Packages Part 2 (Variable Scoping)


© Philip 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.



Examples:

sub myFunction {

print "This is a function";

}
if (@_) {

shift;
print "$_\n";

}

}

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\n";

{
my $var = "second var";
print "Second: $var\n";
}

print "Before Exit: $var\n";


The result will be:
main: main variable
Second: second var
Before Exit: main variable


Explanation
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.



For more information on packages, check out my guide at Self-help guides

Go To Page: 1


The copyright of the article Perl Packages Part 2 (Variable Scoping) in Perl is owned by . Permission to republish Perl Packages Part 2 (Variable Scoping) in print or online must be granted by the author in writing.

Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo