Protecting Global Variables with Local

A problem with changing the global variables for I/O is that they affect every part of the script, including subroutines, library routines, and modules. This can have unexpected (and bad) side effects. The local function, helps avoid problems.

Using Local

local acts a bit like my. It takes one or more variables as arguments and makes them local to a block. However, unlike my, these are not real local variables -- local just saves the variable's current value temporarily, and restores the value when the program exits the block. This means that local can be used to temporarily override global variables.

Use local in a subroutine or other block. This example temporarily changes the value of $/ so that the subroutine can read a paragraph at a time:

  $para1 = read_paragraph();
  $para2 = read_paragraph();
  $para3 = read_paragraph();
 
  sub read_paragraph {
    local $/ = "";    # paragraph mode
    my $paragraph = <>;  # get a paragraph
    return $paragraph;         # and return to caller
  }


<< Previous
Contents >>  

Lincoln D. Stein, lstein@cshl.org
Cold Spring Harbor Laboratory
Last modified: Thu Oct 14 17:06:52 EDT 1999