gpt4 book ai didi

perl - "my"和 "local"之间的差异如何与符号引用交互?

转载 作者:行者123 更新时间:2023-12-03 18:08:06 24 4
gpt4 key购买 nike

之前看过《Effective Perl Programming》一书中的相关内容,但并没有真正理解。今天,我遇到了一个关于这个的问题,如下代码。

my $vname = "a";
my @a = qw(1 2 3);
local @array = @$vname;
foreach(@array) { print "$_\n"; };

它什么都不输出。然后我修改了这一行:
local @a = qw(1 2 3);  

只是用“本地”替换了“我的”,然后它现在可以工作了。所以我想弄清楚它们之间有什么区别。

最佳答案

有一个 perldoc perlfaq7 中回答这个问题的条目:

What's the difference between dynamic and lexical (static) scoping? Between local() and my()?

local($x) saves away the old value of the global variable $x and assigns a new value for the duration of the subroutine which is visible in other functions called from that subroutine. This is done at run-time, so is called dynamic scoping. local() always affects global variables, also called package variables or dynamic variables. my($x) creates a new variable that is only visible in the current subroutine. This is done at compile-time, so it is called lexical or static scoping. my() always affects private variables, also called lexical variables or (improperly) static(ly scoped) variables.

For instance:

sub visible {
print "var has value $var\n";
}

sub dynamic {
local $var = 'local'; # new temporary value for the still-global
visible(); # variable called $var
}

sub lexical {
my $var = 'private'; # new private variable, $var
visible(); # (invisible outside of sub scope)
}

$var = 'global';
visible(); # prints global
dynamic(); # prints local
lexical(); # prints global

Notice how at no point does the value "private" get printed. That's because $var only has that value within the block of the lexical() function, and it is hidden from the called subroutine.

In summary, local() doesn't make what you think of as private, local variables. It gives a global variable a temporary value. my() is what you're looking for if you want private variables.

See Private Variables via
my()
in perlsub
and Temporary Values via
local()
in perlsub
for excruciating details.

关于perl - "my"和 "local"之间的差异如何与符号引用交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12189865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com