Learn Perl #our&my

Difference with our

@Link: http://stackoverflow.com/questions/845060/what-is-the-difference-between-my-and-our-in-perl

Available since Perl 5

my is a way to declare:

  • non-package variables, that are
    • private,
    • new,
    • non-global variables,
    • 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
    • global variables,
    • definitely not private,
    • nor are they necessarily new; and they
    • can be accessed outside the package (or lexical scope) with the qualified namespace, as $package_name::variable.

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.

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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容