Perl 中的“我的"和“我们的"有什么区别? [英] What is the difference between 'my' and 'our' in Perl?
问题描述
我知道 Perl 中的 my
是什么.它定义了一个仅存在于定义它的块范围内的变量.我们的
有什么作用?
I know what my
is in Perl. It defines a variable that exists only in the scope of the block in which it is defined. What does our
do?
our
与 my
有何不同?
推荐答案
our
与 <有何不同code>my 以及 our
有什么作用?
How does our
differ from my
and what does our
do?
总结:
自 Perl 5 起可用,my
是一种声明非包变量的方法,即:
Available since Perl 5, my
is a way to declare non-package variables, that are:
- 私人
- 新
- 非全局
- 与任何包分开,这样变量不能以
$package_name::variable
的形式被访问.
- private
- new
- non-global
- separate from any package, so that the variable cannot be accessed in the form of
$package_name::variable
.
另一方面,我们的
变量是包变量,因此自动:
On the other hand, our
variables are package variables, and thus automatically:
- 全局变量
- 绝对不是私人的
- 不一定是新的
- 可以在包(或词法范围)之外使用限定的命名空间,如
$package_name::variable
.
- global variables
- definitely not private
- not necessarily new
- can be accessed outside the package (or lexical scope) with the
qualified namespace, as
$package_name::variable
.
使用 our
声明变量允许您预先声明变量以便在 use strict
下使用它们code> 不会出现错字警告或编译时错误.从 Perl 5.6 开始,它已经取代了过时的 use vars
,后者只是文件范围的,而不是词法范围的 我们的
.
Declaring a variable with our
allows you to predeclare variables in order to use them under use strict
without getting typo warnings or compile-time errors. Since Perl 5.6, it has replaced the obsolete use vars
, which was only file-scoped, and not lexically scoped as is our
.
例如,package main
中变量 $x
的正式限定名称是 $main::x
.声明 our $x
允许您使用裸 $x
变量而不会受到惩罚(即,不会导致错误),在声明的范围内,当脚本使用use strict
或use strict "vars"
.范围可能是一个、两个或多个包,或者一个小块.
For example, the formal, qualified name for variable $x
inside package main
is $main::x
. Declaring our $x
allows you to use the bare $x
variable without penalty (i.e., without a resulting error), in the scope of the declaration, when the script uses use strict
or use strict "vars"
. The scope might be one, or two, or more packages, or one small block.
这篇关于Perl 中的“我的"和“我们的"有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!