Search code examples
perllexical-scope

Perl scoping and the life of local variables


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};

Solution

  • 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.)