* I updated the answer to note that we've fixed this bug. I kept the old answer around although I added example output to clarify the symptoms.
* This might be a candidate for removal. Index: perlfaq7.pod =================================================================== RCS file: /cvs/public/perlfaq/perlfaq7.pod,v retrieving revision 1.25 diff -u -d -r1.25 perlfaq7.pod --- perlfaq7.pod 8 Aug 2005 02:38:25 -0000 1.25 +++ perlfaq7.pod 10 Oct 2005 18:58:04 -0000 @@ -271,24 +271,40 @@ =head2 What is variable suicide and how can I prevent it? -Variable suicide is when you (temporarily or permanently) lose the -value of a variable. It is caused by scoping through my() and local() -interacting with either closures or aliased foreach() iterator -variables and subroutine arguments. It used to be easy to -inadvertently lose a variable's value this way, but now it's much -harder. Take this code: +This problem was fixed in perl 5.004_05, so preventing it means upgrading +your version of perl. ;) - my $f = "foo"; +Variable suicide is when you (temporarily or permanently) lose the value +of a variable. It is caused by scoping through my() and local() +interacting with either closures or aliased foreach() iterator variables +and subroutine arguments. It used to be easy to inadvertently lose a +variable's value this way, but now it's much harder. Take this code: + + my $f = 'foo'; sub T { - while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" } + while ($i++ < 3) { my $f = $f; $f .= $i; print $f, "\n" } } T; print "Finally $f\n"; +If you are experiencing variable suicide, that C<my $f> in the subroutine +doesn't pick up a fresh copy of the C<$f> whose value is <foo>. The output +shows that inside the subroutine the value of C<$f> leaks through when it +shouldn't, as in this output: + + foobar + foobarbar + foobarbarbar + Finally foo + The $f that has "bar" added to it three times should be a new C<$f> -(C<my $f> should create a new local variable each time through the loop). -It isn't, however. This was a bug, now fixed in the latest releases -(tested against 5.004_05, 5.005_03, and 5.005_56). +C<my $f> should create a new lexical variable each time through the loop. +The expected output is: + + foobar + foobar + foobar + Finally foo =head2 How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}? -- brian d foy, [EMAIL PROTECTED]