What is the difference between my and local in Perl?

Following tutorial explains what is the difference between my and local in Perl?

local vs my in Perl


After looking at variables in Perl we will look at what is the local and my keywords and their impact on the variable and its scope. In simple words my creates a local variable. local doesn't. In other words my makes a variable as private in a lexical scope, and local makes a variable as private in a dynamic scope.

my variable is easier to understand because we all know that my creates a local variable in a block of code or in subroutine i.e. it has lexical scope.
The difference between my and local can be best explained by following example :

Example showing difference between difference between local and my



#!/usr/bin/perl
$localTest = 'GLOBAL';
$myTest = 'GLOBAL';


print "Original Contents\n";
print "Local Test $localTest\n";
print "My Test $myTest\n";


firstSub();
print "Original Contents at the end\n";
print "Local Test $localTest\n";
print "My Test $myTest\n";


sub firstSub {
local $localTest = 'LOCAL_TO_FIRST';
my $myTest = 'LOCAL_TO_FIRST';
print "In first sub\n";
print "Local Test $localTest\n";
print "My Test $myTest\n";


secondSub();
}


sub secondSub {
print "In second sub\n";
print "Local Test $localTest\n";
print "My Test $myTest\n";


}




Output :

Original Contents
Local Test GLOBAL
My Test GLOBAL
In first sub
Local Test LOCAL_TO_FIRST
My Test LOCAL_TO_FIRST
In second sub
Local Test LOCAL_TO_FIRST
My Test GLOBAL
Original Contents at the end
Local Test GLOBAL
My Test GLOBAL


In the above example as we can see two variables one is local and one is defined as my. Then we are calling one function which is modifying the values of both my and local variables. Then we are again calling sub function to print the values. Difference you can notice is my variable changes back to global scope but local not. When we come outside of the function, both values are same as we defined at the start of the code.
In short my creates a local variable which is accessible only within the enclosing lexical block. In contrast, local does not actually make a local variable. It creates a new `local' value for a global variable, which persists until the end of the enclosing block. When control exits the block, the old value is restored. But the variable, and its new `local' value, are still global.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment