Perl中的“我的"和“我们的"有什么区别? [英] What is the difference between 'my' and 'our' in Perl?

查看:77
本文介绍了Perl中的“我的"和“我们的"有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Perl中的my是什么.它定义了一个变量,该变量仅存在于定义该变量的块的范围内. our是做什么的?

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?

ourmy有何不同?

推荐答案

好问题: our my有何区别 our 会做什么?

Great question: 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.


另一方面, our 变量是程序包变量,因此会自动:

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 中使用它们,而不会出现错字警告或编译时错误.从Perl 5.6开始,它已经取代了过时的 use vars ,后者仅是文件作用域,而不是 our 的词法作用域

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屋!

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