perl - 为什么用 "our"声明的变量在文件中可见?

标签 perl variables lexical-scope

从“我们的” perldoc:

our has the same scoping rules as my, but does not necessarily create a variable.


这意味着用our声明的变量在文件中不应该可见,因为file是最大的词法范围。但是这是错误的。为什么?

最佳答案

您可以考虑使用our为程序包全局变量创建一个词法范围的别名。包全局变量可以从任何地方访问。这就是使它们全局化的原因。但是our创建的名称仅在our声明的词法范围内可见。

package A;
use strict;
{
  our $var; # $var is now a legal name for $A::var
  $var = 42; # LEGAL
}

say $var; # ILLEGAL: "global symbol $var requires explicit package name"
say $A::var; # LEGAL (always)

{
  our $var; # This is the same $var as before, back in scope
  $var *= 2; # LEGAL
  say $var; # 84
}

关于perl - 为什么用 "our"声明的变量在文件中可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3626190/

相关文章:

perl - 确定屏幕尺寸的跨平台技术

c - C 中的变量用法

perl - 在 OOP Perl 中调用子例程

arrays - 为什么 Time::HiRes::stat 打破列表下标?

regex - 这个 perl 正则表达式有什么问题?

regex - 如何在替换中使用变量作为修饰符

c++ - Arduino 静态变量声明没有数据类型?

javascript - 使用 Babel.js 将 ES6 箭头函数编译为 Es5

javascript - JavaScript 函数中的词法范围

lisp - Emacs 口齿不清 : why does this sexp cause an invalid-function error?