Always use my; never use local?

做~自己de王妃 提交于 2020-01-03 08:33:46

问题


Implementing dynamic scoping, I was using local. Then I came across this post, which says the following:

Why have local at all? The answer is 90% history. Early versions of Perl only had global variables. local was very easy to implement, and was added to Perl 4 as a partial solution to the local variable problem.

...never use local.

Is its use deprecated, or discouraged? If yes, what is the alternative?


回答1:


The post you linked to is misleading, or at least incomplete. It is true that you should never use local to create a lexical variable. It doesn't do so, and that is what my is for.

However, you should use local when you need its actual functionality: giving a temporary value to a global variable. This is most often used for temporarily setting Perl's special variables. A classic case is something like this:

{
    local $/;
    $entire_file = <$filehandle>;
}

In order to read an entire file at once, you need to set the record separator to undefined. But you only want to do that temporarily; hence local should be used.

This is absolutely not discouraged. It is considered good Perl code.

Update: I see that the article actually has a note which qualifies its "never use local" statement. Still, I think it is misleading to make such a blanket statement. I agree with the critics to which the note is responding. The example above is quite a common, basic case, and there are several other common uses of local in that vein, as well.

I understand that a beginners' tutorial needs to keep things simple, but simple doesn't have to mean inaccurate. "For now, don't worry about local; just use my" would be just as clear and simple, but wouldn't mislead someone into thinking that local should never be used.




回答2:


Use my to create a local variable, which is most of the time what people want.

It's fine to use local for the thing that only local does: setting a different value to a global variable, which will be restored after the current block. That is in no way deprecated. It's stable, well-supported, and is a key Perl feature. (However, it happens not to be something people tend to want any where near as often as creating a local variable. In particular many beginners never need to do this.)

What is discouraged is using local to attempt to create a local variable, because that's what my should be used for. There is never any reason to use local for this.




回答3:


It's not bad advice, actually. As with all programming dicta, the unspoken addendum is "unless you really know what you're doing". There are legitimate use cases for local. But in general, if you think local is the right tool, you should reconsider before proceeding.



来源:https://stackoverflow.com/questions/14457605/always-use-my-never-use-local

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!