My, Our and Local in Perl



My, Our and local

"my"比较常见,"our"和"local"偶尔会出现。查了好多文档,比如perldoc中的perlmod说明,也是比较模糊,而且又提到"lexical"变量的说法,更是让人一头雾水。下面这个文档比较清晰,值得一读。它从Perl发展的历史角度来讲述区别,同时解释了package变量和"lexical"变量的含义。 Coping with Scoping

举一个例子,加深理解。

package abc;
use strict;
use warnings;

$VERSION = 0.1;

sub get_ver {$VERSION}

package main;
print "step 1: $abc::VERSION\n";
print "step 2: ". abc::get_ver();

如上面代码所示,我们想在"package abc"中使用具有全局属性的package变量"$VERSION",但是由于用了"use strict",所以上面一段代码编译会报如下错。

Global symbol "$VERSION" requires explicit package name (did you forget to declare "my $VERSION"?) at a.pl line 7.
Global symbol "$VERSION" requires explicit package name (did you forget to declare "my $VERSION"?) at a.pl line 10.
Execution of a.pl aborted due to compilation errors.

根据提示我们可以修改成下面这样,在package abc内部使用自己的变量也要加上package名称做前缀:

package abc;
use strict;
use warnings;

$abc::VERSION = 0.1;

sub get_ver {$abc::VERSION}

package main;
print "step 1: $abc::VERSION\n";
print "step 2: ". abc::get_ver();

为了不这样麻烦,出现了our函数,这样我们就能更优雅一点的使用package变量了:

package abc;
use strict;
use warnings;

our $VERSION = 0.1;

sub get_ver {$VERSION}

package main;
print "step 1: $abc::VERSION\n";
print "step 2: ". abc::get_ver();