D
David McNerney
Hello all... I'm wondering if anyone can help me make sense of some
strange behavior that just bit me. It would appear that it's possible
for a lexical array declared inside a function to retain values between
function invocations, if said array is declared but not initialized in
a single-line "if" statement. I've reduced my problem to the test case
below, which performs per the comments on Perl 5.8.6 (Mac OSX Darwin)
and Perl 5.8.5 (Red Hat Linux Enterprise 4 Update 1). Much thanks in
advance for any insight anyone can provide. -- David
#!/usr/bin/perl -w
use strict;
sub function1
{
# PROBLEM HERE: if $_[0] is false here on successive invocations,
# @list is not cleared on the 2nd and later cycles, and any values
# added to it build up.
#
my @list = ("a") if $_[0];
# Uncomment this, and comment out the one above, and of course the
# strange behavior is gone
#
#my @list;
push(@list,"b") if $_[1];
print "list was: ".join(" ", @list)."\n";
}
&function1(1,1); # should print "a b", and does
&function1(1,0); # should print "a", and does
&function1(0,1); # should print "b", and does
# Problems begin here
#
&function1(0,0); # should print "", but prints "b"
&function1(0,1); # should print "b", but prints "b b"
&function1(0,1); # should print "b", but prints "b b b"
&function1(0,1); # should print "b", but prints "b b b b"
&function1(0,1); # should print "b", but prints "b b b b b"
# Ok again
#
&function1(1,0); # should print "a", and does
strange behavior that just bit me. It would appear that it's possible
for a lexical array declared inside a function to retain values between
function invocations, if said array is declared but not initialized in
a single-line "if" statement. I've reduced my problem to the test case
below, which performs per the comments on Perl 5.8.6 (Mac OSX Darwin)
and Perl 5.8.5 (Red Hat Linux Enterprise 4 Update 1). Much thanks in
advance for any insight anyone can provide. -- David
#!/usr/bin/perl -w
use strict;
sub function1
{
# PROBLEM HERE: if $_[0] is false here on successive invocations,
# @list is not cleared on the 2nd and later cycles, and any values
# added to it build up.
#
my @list = ("a") if $_[0];
# Uncomment this, and comment out the one above, and of course the
# strange behavior is gone
#
#my @list;
push(@list,"b") if $_[1];
print "list was: ".join(" ", @list)."\n";
}
&function1(1,1); # should print "a b", and does
&function1(1,0); # should print "a", and does
&function1(0,1); # should print "b", and does
# Problems begin here
#
&function1(0,0); # should print "", but prints "b"
&function1(0,1); # should print "b", but prints "b b"
&function1(0,1); # should print "b", but prints "b b b"
&function1(0,1); # should print "b", but prints "b b b b"
&function1(0,1); # should print "b", but prints "b b b b b"
# Ok again
#
&function1(1,0); # should print "a", and does