- 论坛徽章:
- 0
|
原帖由 shake863 于 2008-5-5 17:27 发表 ![]()
##############################
my $hello = "How are you doing?";
sub test{
local $hello = "insub";
print $hello;
}
test();
这个出错可以理解,因为对已经用my声明的变量 不能再用local声 ...
你需要明白
1.
- $a = "att";
- my $a = "btt";
复制代码
这样是定义了两个变量,第一个是global的,第二个是lexicall的
2.
这样只定义了一个变量
引用effective perl programming中的例子
- my $compile_time;
- $compile_time;
- print join " ", keys (%::);
- $compile_time; #actually create two variables
- my $compile_time;
- print join " ", keys (%::);
复制代码What these examples demonstrate is that my variables do not "live" in the package symbol tables. In the example with my $compile_time first, there is only one variable named $compile_time in the file, and it never gets into the package symbol table. In the other example, there are two separate variables named $compile_time : the global one in the symbol table, and my $compile_time , which is not in a symbol table.
你可以执行下代码,自己验证下
回到你的问题
由于你的sub test1 definition在前
所以首先创建了一个全局变量$hello (local只能用于全局的变量,用my定义的不存在于package 的symbol table中)
然后后来又创建了一个局部变量$hello
所以共有两个变量
执行函数的时候调用的是全局那个变量
建议弄清楚my local use的区别
同时最好加上use strict;
这样可以避免很多错误
引用programming perl中chapter 4的话
my ($nose, @eyes, %teeth);
our ($House, @Autos, %Kids);
local (*Spouse, $phone{HOME});
Each of these modifiers offers a different sort of "confinement" to the variables they modify. To oversimplify slightly: our confines names to a scope, local confines values to a scope, and my confines both names and values to a scope.
Each of these constructs may be assigned to, though they differ in what they actually do with the values, since they have different mechanisms for storing values. They also differ somewhat if you don't (as we didn't above) assign any values to them: my and local cause the variables in question to start out with values of undef or (), as appropriate; our, on the other hand, leaves the current value of its associated global unchanged.
Repeated our declarations do not meaningfully nest. Every nested my produces a new variable, and every nested local a new value. But every time you use our, you're talking about the same global variable, irrespective of nesting. When you assign to an our variable, the effects of that assignment persist after the scope of the declaration. That's because our never creates values; it just exposes a limited form of access to the global, which lives forever:
our $PROGRAM_NAME = "waiter";
{
our $PROGRAM_NAME = "server";
# Code called here sees "server".
...
}
# Code executed here still sees "server".
[ 本帖最后由 churchmice 于 2008-5-5 18:34 编辑 ] |
|