in reply to Re^3: scope of variable
in thread scope of variable
bart's comment on closures is exactly the reason for your problem. See this simplified example:
use strict; use warnings; sub func { my $calls = shift; my $strange = "Call $calls"; print "In func (start): $strange\n"; sub subfunc1 { print "In subfunc1: $strange\n"; $strange .= " even"; } sub subfunc2 { print "In subfunc2: $strange\n"; } subfunc1(); subfunc2(); print "In func (end): $strange\n"; } func(1); func(2); func(3); func(4);
which creates the following output (including a couple of warnings!):
Variable "$strange" will not stay shared at closure2.pl line 10. Variable "$strange" will not stay shared at closure2.pl line 15. In func (start): Call 1 In subfunc1: Call 1 In subfunc2: Call 1 even In func (end): Call 1 even In func (start): Call 2 In subfunc1: Call 1 even In subfunc2: Call 1 even even In func (end): Call 2 In func (start): Call 3 In subfunc1: Call 1 even even In subfunc2: Call 1 even even even In func (end): Call 3 In func (start): Call 4 In subfunc1: Call 1 even even even In subfunc2: Call 1 even even even even In func (end): Call 4
which clearly demonstrates that the variable $strange in the subfuncs is decoupled from $strange in func in the second and subsequent calls to func. The warnings also tell the same story.
UPDATE: Compare to the following:
use strict; use warnings; my $strange; sub subfunc1 { print "In subfunc1: $strange\n"; $strange .= " even"; } sub subfunc2 { print "In subfunc2: $strange\n"; } sub func { my $calls = shift; $strange = "Call $calls"; print "In func (start): $strange\n"; subfunc1(); subfunc2(); print "In func (end): $strange\n"; } func(1); func(2); func(3); func(4);
whose output is probably what you expected. Whether or not this is good style is a diffent question ...
|
|---|