What is the difference between my and local in Perl?

前端 未结 14 1614
佛祖请我去吃肉
佛祖请我去吃肉 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:56

    local is an older method of localization, from the times when Perl had only dynamic scoping. Lexical scoping is much more natural for the programmer and much safer in many situations. my variables belong to the scope (block, package, or file) in which they are declared.

    local variables instead actually belong to a global namespace. If you refer to a variable $x with local, you are actually referring to $main::x, which is a global variable. Contrary to what it's name implies, all local does is push a new value onto a stack of values for $main::x until the end of this block, at which time the old value will be restored. That's a useful feature in and of itself, but it's not a good way to have local variables for a host of reasons (think what happens when you have threads! and think what happens when you call a routine that genuinely wants to use a global that you have localized!). However, it was the only way to have variables that looked like local variables back in the bad old days before Perl 5. We're still stuck with it.

提交回复
热议问题