Perl - my, local, our (最近在学perl)

来源:互联网 发布:模拟股市软件下载 编辑:程序博客网 时间:2024/05/21 22:53

最近碰到了Perl - my, local, our 这个问题,收集了下!

首先给出一个摘录过来的实例,运行完后自己仔细看看就知道my和local的区别了,实例后没懂得我在分析。

##############################################
#!/usr/bin/perl
# not strict clean, yet, but just wait
$global = "I'm the global version";
show_me('At start');
lexical();
localized();
show_me('At end');
sub show_me
{
my $tag = shift;
print "$tag: $global/n"
}
sub lexical
{
my $global = "I'm in the lexical version";
print "In lexical(), /$global is --> $global/n";
show_me('From lexical()');
}
sub localized
{
local $global = "I'm in the localized version";
print "In localized(), /$global is --> $global/n";
show_me('From localized');
}
##############################################

运行结果是
***************************************************
At start: I'm the global version
In lexical(), $global is --> I'm in the lexical version
From lexical: I'm the global version
In localized(), $global is --> I'm in the localized version
From localized: I'm in the localized version
At end: I'm the global version
***************************************************

分析:
1.my和local都只在一个block里有效,出去就失效
2.但是local的变量可以继续在这个block中调用的子程序中存在
3.如果有与外界同名的变量,两者在block退出后都不影响外界同名变量

our:

如果在一个block中有一个my修饰的变量和外界的一个变量同名,而且又需要在这个block中使用外接变量时,两个办法:
第一个办法,用main的package修饰这个变量名,$main::global
第二个办法,用our修饰,our $global,那么该block中接下来出现的所有$global都是外界的global