icon Top 9 categories map      RocketAware > Perl >

What is variable suicide and how can I prevent it?

Tips: Browse or Search all pages for efficient awareness of Perl functions, operators, and FAQs.



Home

Search Perl pages


Subjects

By activity
Professions, Sciences, Humanities, Business, ...

User Interface
Text-based, GUI, Audio, Video, Keyboards, Mouse, Images,...

Text Strings
Conversions, tests, processing, manipulation,...

Math
Integer, Floating point, Matrix, Statistics, Boolean, ...

Processing
Algorithms, Memory, Process control, Debugging, ...

Stored Data
Data storage, Integrity, Encryption, Compression, ...

Communications
Networks, protocols, Interprocess, Remote, Client Server, ...

Hard World
Timing, Calendar and Clock, Audio, Video, Printer, Controls...

File System
Management, Filtering, File & Directory access, Viewers, ...

    

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() interator 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 is a bug, and will be fixed.


Source: Perl FAQ: Perl Language Issues
Copyright: Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
Next: How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regexp}?

Previous: What's a closure?



(Corrections, notes, and links courtesy of RocketAware.com)


[Overview Topics]

Up to: PERL




Rapid-Links: Search | About | Comments | Submit Path: RocketAware > Perl > perlfaq7/What_is_variable_suicide_and_how.htm
RocketAware.com is a service of Mib Software
Copyright 2000, Forrest J. Cavalier III. All Rights Reserved.
We welcome submissions and comments