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:

    my $f = "foo";
    sub T {
      while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" }
    }
    T;
    print "Finally $f\n";
The $f that has "bar" added to it three times should be a new $f (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).
Back to perlfaq7