|
|
|
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.
print "This is a function";
}
shift;
}
} The my FunctionVariables defined using the my function are visible only within the block and its subordinate blocks. So if you have something like this:
{
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.
|
|
|
|
|
|
|
|