开发者

Perl scoping and the life of local variables

开发者 https://www.devze.com 2023-02-25 12:04 出处:网络
How long does the memory location allocated by a local variable in Perl live for (both for arrays, hashes and scalars)? For instance:

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 liv开发者_运维技巧e 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};


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 call routine (even recursively). (Perl 5.10 introduced state variables, which are rather like a C static.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号