12

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};
cjm
  • 61,471
  • 9
  • 126
  • 175
rubixibuc
  • 7,111
  • 18
  • 59
  • 98
  • Did you try this code? You could have at least answered the first question yourself. – runrig Apr 15 '11 at 14:42
  • 4
    @runrig, there's a difference between "it happens to work in this particular case" and "this is actually supposed to work". Running the code will only tell you the first. – cjm Apr 15 '11 at 17:16

1 Answers1

22

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

cjm
  • 61,471
  • 9
  • 126
  • 175