Friday, September 17, 2010

Difference between "my" and "local"

1) Quick summary: 'my' creates a new variable, 'local' temporarily amends the value of a variable

2) The variables declared with "my" can live only within the block it was defined and cannot get its visibility in the inherited functions called within that block, but one defined with "local" can live within the block and have its visibility in the functions called within that block.

3) The variables declared with my() are visible only within the scope of the block which names them. They are not visible outside of this block, not even in routines or blocks that it calls. local() variables, on the other hand, are visible to routines that are called from the block where they are declared. Neither is visible after the end (the final closing curly brace) of the block at all.



4) My: 

My creates a new variable and gives a lexical scope for that variable.The variable is not visible outside the block in which it is defined.
 

 Local:

Local saves the value of a global variable.It never creates a new variable. Here also the variable is not accessible outside the block but it is visible in the subroutine which is called from the original block. My is more preferring than local . But in various places local is useful where my is illegal.



Example:

#!/usr/local/bin/perl
$var=4;
print $var, "\n";
&sub_routine1;
print $var, "\n";
&sub_routine2;
print $var, "\n";

#subroutine

sub sub_routine1 {
        local $var = 10;
        print $var, "\n";
        &sub_routine2;
        print $var, "\n";
}

sub sub_routine2 {
        $var++;

}



OUTPUT:

4
10
11
4
5

1 comment:

  1. nice explanation...if u giv some examples it is useful to new learners....

    ReplyDelete