What is the difference between my and local in Perl?

前端 未结 14 1684
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 03:13

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?

14条回答
  •  孤街浪徒
    2020-12-01 03:54

    http://perldoc.perl.org/perlsub.html#Private-Variables-via-my()

    Unlike dynamic variables created by the local operator, lexical variables declared with my are totally hidden from the outside world, including any called subroutines. This is true if it's the same subroutine called from itself or elsewhere--every call gets its own copy.

    http://perldoc.perl.org/perlsub.html#Temporary-Values-via-local()

    A local modifies its listed variables to be "local" to the enclosing block, eval, or do FILE --and to any subroutine called from within that block. A local just gives temporary values to global (meaning package) variables. It does not create a local variable. This is known as dynamic scoping. Lexical scoping is done with my, which works more like C's auto declarations.

    I don't think this is at all unclear, other than to say that by "local to the enclosing block", what it means is that the original value is restored when the block is exited.

提交回复
热议问题