Previous Page
Next Page

5.3. Localization

If you're forced to modify a package variable, localize it.

Occasionally you will have no choice but to use a package variable, usually because some other developer has made it part of the module's public interface. But if you change the value of that variable, you're making a permanent decision for every other piece of code in your program that uses the module:

    use YAML;
    $YAML::Indent = 4;       # Indent hereafter 4 everywhere that YAML is used

By using a local declaration when making that change, you restrict its effects to the dynamic scope of the declaration:


    use YAML;
    local $YAML::Indent = 4; 
# Indent is 4 until control exits current scope

That is, by prefacing the assignment with the word local, you can temporarily replace the package variable $YAML::Indent until control reaches the end of the current scope. So any calls to the various subroutines in the YAML package from within the current scope will see an indent value of 4. And after the scope is exited, the previous indent value (whatever it was) will be restored.

This is much more neighbourly behaviour. Rather than imposing your personal preferences on the rest of the program, you're imposing them only on your small corner of the code.

    Previous Page
    Next Page