Scope avaible in perl:
1)my
2)local
3)our
my scope:
1)By this scope we mean that variables defined with my are accessible only within the block
and it is not even accessible for the functions called from the block.
2)here it creates a lexical scope for the variable(only accessible within the block)
3)it is more preferrable than the other scope as it does not overwrite the value .
4)it makes a variable private in lexical scope.
local scope:
1)Here the temp variable is created in the dynamic scope.
2)The dynamic scope it means the variable not only visible within the block but it is also visible in the function called from the block.
3)it is mainly used in cases where using "my" may prove illegal especially for special variables.
4)it makes variable private in a dynamic scope.
our scope:
1)It is definitely not private and it is the default thing which is used when you don't specify any scope;
2)it is global
3)Even outside the package it can be accessed by using Packagename::variablename;
Example:
Content of Perl file:
firstSub("AAAAA", "BBBBB");
sub firstSub{
local ($firstVar) = $_[0];
my($secondVar) = $_[1];
print("firstSub: firstVar = $firstVar\n");
print("firstSub: secondVar = $secondVar\n\n");
secondSub();
print("firstSub: firstVar = $firstVar\n");
print("firstSub: secondVar = $secondVar\n\n");
}
sub secondSub{
print("secondSub: firstVar = $firstVar\n");
print("secondSub: secondVar = $secondVar\n\n");
$firstVar = "ccccC";
$secondVar = "DDDDD";
print("secondSub: firstVar = $firstVar\n");
print("secondSub: secondVar = $secondVar\n\n");
}
Output:
G:\perl_programs>perl perl_scope1.pl
firstSub: firstVar = AAAAA
firstSub: secondVar = BBBBB
secondSub: firstVar = AAAAA
secondSub: secondVar =
secondSub: firstVar = ccccC
secondSub: secondVar = DDDDD
firstSub: firstVar = ccccC
firstSub: secondVar = BBBBB
Analysis:
As you may see the firstvar declared as local scope is visible in secondSub routine
But secondVar declared as my scope is not visible in the routine secondSb and it is empty.
And the other thing you may notice is firstVar variable intialized as "ccccC" overwrites the value in the block from which it was called.But in the case of secondVar variable it is not overwritten.