in reply to Tricky scope problem
I have a global variable going out of scope
Global variables don't go out of scope. That's because they are global. In the code you've posted there's no global variable at all. There's a $gVar which is lexically scoped via my on file level.
Do you mean, $gVar doesn't hold the last hashref from $listOfHashRef after calling Foo() ? That's because the $gVar as a foreach iterator aliases (masks) the outer $gVar. Consider:
use strict; sub generateList { my $ref; push @$ref, { funPtr => do { my $x = $_; sub { print "in $x\n" } } + } for qw(foo bar); $ref; } my $gVar; sub Foo { my $listOfHashRef = generateList(); my $functionPtr; foreach (@$listOfHashRef) { $gVar = $_; $functionPtr = $gVar->{funPtr}; # Assert: $gVar has all of its values here $functionPtr->(); } } # Assert: The $gVar->{funPtr} does indeed point to Bar sub Bar { print "$gVar\n"; # Assert: $gVar is null } Foo(); Bar(); __END__ in foo in bar HASH(0x88a1660)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Tricky scope problem
by Anonymous Monk on Apr 13, 2009 at 14:41 UTC | |
by shmem (Chancellor) on Apr 13, 2009 at 19:52 UTC |