本文介绍了为什么用“我们的"声明变量?跨文件可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自我们的" perldoc :

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

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?

推荐答案

您可以考虑使用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 by our is only visible within the lexical scope of the our declaration.

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
}

这篇关于为什么用“我们的"声明变量?跨文件可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:58