为什么变量用“our”声明?跨文件可见?
From the "our" perldoc:
our has the same scoping rules as my, but does not necessarily create a variable.
This means that variables declared with our
should not be visible across files, because file is the largest lexical scope. But this is not true. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以考虑
our
为包全局变量创建一个词法范围的别名。包全局变量可以从任何地方访问;这就是它们全球化的原因。但是our
创建的名称仅在our
声明的词法范围内可见。You can consider
our
to create a lexically-scoped alias to a package global variable. Package globals are accessible from everywhere; that's what makes them global. But the name created byour
is only visible within the lexical scope of theour
declaration.您已经有了一个很好的答案,但这也许也会有帮助。
our
声明结合了my
和use vars
的各个方面。它的功能与use vars
类似,因为它声明了包变量;但是,以这种方式声明的变量具有词法作用域,并且不能在声明它们的作用域之外访问(除非您使用变量的完全限定名称)。此外,用our
声明的变量在其整个词法范围内都是可见的,甚至跨包边界。这是我不久前添加到 Perl 笔记中的一张表。例如,请参阅 这个答案。
You have a good answer already, but perhaps this will be helpful as well.
The
our
declaration combines aspects ofmy
anduse vars
. It functions similarly touse vars
in that it declares package variables; however, variables declared in this way are lexically scoped and cannot be accessed outside the scope in which they were declared (unless you use the fully qualified name of the variable). In addition, a variable declared withour
is visible across its entire lexical scope, even across package boundaries.Here's a table that I added to my Perl notes a while back. For an example, see this SO answer.