tags:

views:

586

answers:

5

In the following code upto what scope the anonymous array referred by $ref is available.

mod1.pm:
package mod1;
sub do_something{
 .....
 my $array_ref = ["elemnt1","elmnt2"] ;
 return $array_ref ;
}
1;

file.pl
use mod1;
my $ref = mod1::do_something() ;
print "$ref->[0]  $ref->[1] " ; #works
+2  A: 

It is available as long as anyone has a reference to it.

cube
+6  A: 

If I'm understanding the question correctly the scope of $ref is all of file2.pl

In do_something you are creating an anonymous array, so it sits on the heap, and isn't part of any scope. So the reference can be passed around and will be available anywhere until there is no longer a reference pointing to it.

Tom
yeah, and even a reference to a `my` variable (if `do_something` did return `\$ref_array`) would be detached from the scope. Perl is not C, things are available "as long as anyone has a reference to it", as cube said below.
Massa
Minor correction: The scope of `$ref` isn't quite all of file2.pl. It's visible from the point at which it is declared until the end of the file.
Michael Carman
A: 

Its scope is limited to the do_something subroutine where it's created until it's returned and stored in $ref. Once it's stored in $ref in file2.pl, it is in scope anywhere in file2.pl.

Adrian Dunston
+12  A: 

From the question it sounds like you are struggling with the difference between the scope of a variable, and the persistence of data pointed to by a reference. The data ["elemnt1","elmnt2"] is assigned to a variable ($array_ref) that goes out of scope at the end of do_something. However, because it is returned, there is a reference to the data, and it persists even when $array_ref goes out of scope.

Last time I checked, perl used reference-counting for garbage collection, so that array will not be garbage-collected until the last reference to it goes out of scope, e.g., if you unset $ref at the end of your example.

Alex Feinman
+8  A: 

Alex Feinman has the right idea. Variable names have scope, data does not. Asking for the scope of an anonymous array is like asking for the scope of a string. A string is accessible so long as there is a variable that provides direct or indirect (i.e. a reference) access to it.

Chas. Owens
It's like asking for the scope of `2`
Brad Gilbert