FAQ 7.14 What is variable suicide and how can I prevent it?

FAQ 7.14 What is variable suicide and how can I prevent it?

am 20.10.2007 03:03:02 von PerlFAQ Server

This is an excerpt from the latest version perlfaq7.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

------------------------------------------------------------ --------

7.14: What is variable suicide and how can I prevent it?

This problem was fixed in perl 5.004_05, so preventing it means
upgrading your version of perl. ;)

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";

If you are experiencing variable suicide, that "my $f" in the subroutine
doesn't pick up a fresh copy of the $f whose value is . The output
shows that inside the subroutine the value of $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 $f "my $f"
should create a new lexical variable each time through the loop. The
expected output is:

foobar
foobar
foobar
Finally foo



------------------------------------------------------------ --------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.