Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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};
like image 716
rubixibuc Avatar asked Apr 15 '11 06:04

rubixibuc


People also ask

What is the scope of variable in Perl?

The scope of a variable is the part of the program where the variable is accessible. A scope is also termed as the visibility of the variables in a program. In Perl, we can declare either Global variables or Private variables. Private variables are also known as lexical variables.

Is Perl dynamically scoped?

Perl also supports dynamically scoped declarations. A dynamic scope also extends to the end of the innermost enclosing block, but in this case "enclosing" is defined dynamically at run time rather than textually at compile time.

What is a local variable What is the scope of a local variable?

In computer science, a local variable is a variable that is given local scope. A local variable reference in the function or block in which it is declared overrides the same variable name in the larger scope.

What is @_ and $_ in Perl?

$_ - The default input and pattern-searching space. @_ - Within a subroutine the array @_ contains the parameters passed to that subroutine. $" - When an array or an array slice is interpolated into a double-quoted string or a similar context such as /.../ , its elements are separated by this value.


1 Answers

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

like image 63
cjm Avatar answered Oct 03 '22 18:10

cjm