perlscoping

What is the difference between my and local in Perl?


I am seeing both of them used in this script I am trying to debug and the literature is just not clear. Can someone demystify this for me?


Solution

  • Dynamic Scoping. It is a neat concept. Many people don't use it, or understand it.

    Basically think of my as creating and anchoring a variable to one block of {}, A.K.A. scope.

    my $foo if (true); # $foo lives and dies within the if statement.
    

    So a my variable is what you are used to. whereas with dynamic scoping $var can be declared anywhere and used anywhere. So with local you basically suspend the use of that global variable, and use a "local value" to work with it. So local creates a temporary scope for a temporary variable.

    $var = 4;
    print $var, "\n";
    &hello;
    print $var, "\n";
    
    # subroutines
    sub hello {
         local $var = 10;
         print $var, "\n";
         &gogo; # calling subroutine gogo
         print $var, "\n";
    }
    sub gogo {
         $var ++;
    }
    

    This should print:

    4
    10
    11
    4