Locally Redefine

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.";

The 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 undef?

The test in Listing 6-9 shows how to use local to override open for the duration of the test and only within the scope of the test. Perl has block scope, so any reference to open within the block invokes the anonymous subroutine that simply returns undef.

Listing 6-9: Using Perl local to redefine the open function within the test

sub test_override_open {
  local *open = sub { return undef; };
  # Invoke the code that uses open
  ...
} # local definition of open goes away

Perl allows you to do this for variables as well as functions. The redefinition can happen regardless of the scope of the item being redefined. For example, the following line is used to turn off warnings from the Archive::Extract module only after the statement within the block that contains it.

local $Archive::Extract::WARN = 0;

This kind of local redefinition of symbols provides great power but is only available in a small number of languages.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.111.208