No, it's not a dangling pointer. I'm not entirely sure references (pointers) can be made to dangle in Perl; I suppose it could be done if someone wanted to try hard enough. But Perl has automatic garbage collection.
This little demo might prove interesting:
no strict; # just for this demo
use warnings;
my $ref = \do{ my $anon = 42 };
my $deref = ${ $ref };
print '$ref: ' , "$ref\n";
print '$deref: ' , "$deref\n";
print '$anon: ' , "$anon\n";
__END__
Output:
Name "main::anon" used only once: possible typo at ./anon-scalar-ref-d
+emo.pl line 9.
$ref: SCALAR(0x9dbefd8)
$deref: 42
Use of uninitialized value $anon in concatenation (.) or string at ./a
+non-scalar-ref-demo.pl line 9.
$anon:
Explanation:
- Line 4 creates a variable, $anon, which is undefined at the outset, associates it with a memory location, and immediately puts 42 into that memory location. This assignment is enclosed in a do-block; so the variable goes out of scope almost as soon as it's created. However, do{} gets to act before that destruction and evaluates to the contents of the block: the variable that's about to be destroyed. The backslash takes a reference to that memory location and the variable name is destroyed. Finally, that reference is assigned to $ref.
- Line 5 dereferences $ref, finding the memory location originally associated with $anon, and assigns that value to $deref.
- Line 7 correctly prints the memory location originally associated with $anon. The memory has not been deallocated, since $ref still points to it.
- Line 8 correctly prints the value stored in $deref (42).
- Line 9 raises a compile-time warning, since the $anon in that print statement is really $main::anon and not the my $anon to which we assigned in line 4 and is now out of scope. A run-time warning is also issued about the attempt to print that undefined variable.
I encourage you to copy this demo and fool around with it until you feel more comfortable with references. Suggest changing the assignment, eliminating the do-block, taking a reference to $ref, and dropping braces in various places to force scope. (One experiment at a time!) Here's a few other changes to try:
my $ref = \do{ @arr = (1, 2, 3) };
or:
my @arr = (1, 2, 3);
my $ref = \@arr;
or:
my $ref = \(1, 2, 3);
or:
my $ref = [1, 2, 3];
Can you guess for which of the above print @arr; will not raise a warning?
Strongly suggest you try perldoc perlref, which goes into much greater detail. Mark Dominus' perldoc perlreftut is an easy introduction.
|