Some languages let you redefine any variable or function within a scope and only for the duration of that scope. Let’s say, for example, that we want to test a Perl subroutine that uses the
open function. Consider how you might force an error in a test of the following line of idiomatic Perl.
open $fh, "<", "input.txt" or die "Could not open input file.";
open function returns a nonzero value on success and the Perl undefined value otherwise. The short-circuit evaluation of the
or evaluates the
open as true on success and therefore skips the
die statement. But how would we get
open to return
The test in Listing 6-9 shows how to use
local to override
open for the duration of the test ...