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.
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
} |
|
| Contents |