总是使用我的;从不使用本地? [英] Always use my; never use local?

查看:46
本文介绍了总是使用我的;从不使用本地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现动态范围,我使用了local.然后我看到了 this 帖子,上面写着:

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

为什么要本地化?答案是 90% 的历史.早期版本Perl 只有全局变量.local 很容易实现,并且被添加到 Perl 4 作为局部变量的部分解决方案问题.

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.

...永远不要使用本地.

它的使用是被弃用还是不鼓励?如果是,替代方案是什么?

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

推荐答案

您链接的帖子具有误导性,或者至少是不完整的.确实,您永远不应该使用 local 来创建词法变量.它没有这样做,这就是 my 的用途.

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.

但是,当您需要local 的实际功能时,您应该使用它:为全局变量提供一个临时值.这最常用于临时设置 Perl 的特殊变量.一个经典案例是这样的:

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>;
}

为了一次读取整个文件,您需要将记录分隔符设置为未定义.但你只想暂时这样做;因此应该使用 local.

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.

这绝对不气馁.它被认为是好的 Perl 代码.

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

更新:我看到这篇文章实际上有一个注释,可以证明其从不使用本地"声明.尽管如此,我认为做出这样一个笼统的声明是具有误导性的.我同意该说明所回应的批评.上面的例子是一个很常见的基本情况,在这种情况下,local 还有其他几种常见的用法.

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.

我知道初学者的教程需要保持简单,但简单并不一定意味着不准确.现在,不要担心 local;只需使用 my" 将同样清晰和简单,但不会误导他人认为应该永远使用local.

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.

这篇关于总是使用我的;从不使用本地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆