work, study, life ..........

Wednesday, April 15, 2009

perl 中变量定义my 和 local的区别

my函数在perl官方文档中,是这样定义的:
* my EXPR
* my TYPE EXPR
* my EXPR : ATTRS
* my TYPE EXPR : ATTRS

A my declares the listed variables to be local (lexically) to the enclosing block, file, or eval. If more than one value is listed, the list must be placed in parentheses.
也就是说my用在封装块,文件,或者是eval中声明局部变量列表用.如果有多于一个变量值的列表, 必须他们放置在圆括号里面.例如在下面的perl中做了全局变量和局部变量的对比:

#/usr/bin/perl
# use warnings;

$x = 10;

test();

sub test{
my $x = 20;
print "The first \$x is $x.\n";
}

print "The second \$x is $x.\n";

显示结果:
The first $x is 20.
The second $x is 10.

在上面的实例中,看到了全局变量$x和局部变量$x的不同值的有效性.

在看看local:
create a temporary value for a global variable (dynamic scoping)

local为全局变量(动态范围)定义.local赋予变量的值在执行时间才有效,也就是为当前的代码块中的变量赋予一个临时值,其值有效性包括当前代码块中含有其他的程序。可以看看下面的perl程序:
#!/usr/bin/perl
#
use warnings;
use strict;

my $x=2;
$_ = "true";
{
my $x = 10;
local $_ = "false";
somesub();
}

somesub();

sub somesub{
print "\$x is $x\n";
print "\$_ is $_\n";
}

显示结果:
$x is 2
$_ is false
$x is 2
$_ is true

尽管有$x = 10 这条语句,但仅仅对从 "my $x = 10;" 到 "somesub();"这块造成影响. 局部变量会考虑它的实际内容,而不是按照顺序执行.所以当我们调用somesub时,其实$x的值还是2.


不过,一般不推荐使用local定义局部变量.

No comments: