Perl 作用域和局部变量的生命周期
Perl 中的局部变量分配的内存位置可以存在多久(数组、散列和标量)?例如:
sub routine
{
my $foo = "bar";
return \$foo;
}
函数返回后,你还能访问内存中的字符串“bar”
吗?它会存在多久,它是否类似于 C 中的静态变量,或者更像是在堆外声明的变量?
基本上,这在这种情况下有意义吗?
$ref = routine()
print ${$ref};
How long does the memory location allocated by a local variable in Perl live for (both for arrays, hashes and scalars)? For instance:
sub routine
{
my $foo = "bar";
return \$foo;
}
Can you still access the string "bar"
in memory after the function has returned? How long will it live for, and is it similar to a static variable in C or more like a variable declared off the heap?
Basically, does this make sense in this context?
$ref = routine()
print ${$ref};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,该代码可以正常工作。
Perl 使用引用计数,因此只要有人引用该变量,该变量就会存在。 Perl 的 词法变量 有点像 C 的自动变量变量,因为当您离开作用域时它们通常会消失,但它们也像堆上的变量一样,因为您可以返回对变量的引用,它就会正常工作。
它们与 C 的静态变量不同,因为每次调用
routine
(甚至递归地)时都会得到一个新的$foo
。 (Perl 5.10 引入了状态
变量,很像 C 静态。)Yes, that code will work fine.
Perl uses reference counting, so the variable will live as long as somebody has a reference to it. Perl's lexical variables are sort of like C's automatic variables, because they normally go away when you leave the scope, but they're also like a variable on the heap, because you can return a reference to one and it will just work.
They're not like C's static variables, because you get a new
$foo
every time you callroutine
(even recursively). (Perl 5.10 introducedstate
variables, which are rather like a C static.)