JavaScript EditorFreeware JavaScript Editor     Perl Tutorials 

Main Page Previous Section Next Section

Recipe 12.2 Trapping Errors in require or use

12.2.1 Problem

You need to load in a module that might not be present on your system. This normally results in a fatal exception. You want to detect and trap these failures.

12.2.2 Solution

Wrap the require or use in an eval, and wrap the eval in a BEGIN block:

# no import
    unless (eval "require $mod; 1") {
        warn "couldn't require $mod: $@";

# imports into current package
    unless (eval "use $mod; 1") {
        warn "couldn't use $mod: $@";

12.2.3 Discussion

You usually want a program to fail if it tries to load a module that is missing or doesn't compile. Sometimes, though, you'd like to recover from that error, perhaps trying an alternative module instead. As with any other exception, you insulate yourself from compilation errors with an eval.

You don't want to use eval { BLOCK }, because this traps only runtime exceptions, and use is a compile-time event. Instead, you must use eval "string" to catch compile-time problems as well. Remember, require on a bareword has a slightly different meaning than require on a variable. It adds a ".pm" and translates double-colons into your operating system's path separators, canonically / (as in URLs), but sometimes \, :, or even . on some systems.

If you need to try several modules in succession, stopping at the first one that works, you could do something like this:

    my($found, @DBs, $mod);
    $found = 0;
    @DBs = qw(Giant::Eenie Giant::Meanie Mouse::Mynie Moe);
    for $mod (@DBs) {
        if (eval "require $mod") {
            $mod->import( );         # if needed
            $found = 1;
    die "None of @DBs loaded" unless $found;

We wrap the eval in a BEGIN block to ensure the module-loading happens at compile time instead of runtime.

12.2.4 See Also

The eval, die, use, and require functions in Chapter 32 of Programming Perl and in perlfunc(1); Recipe 10.12; Recipe 12.3

    Main Page Previous Section Next Section

    JavaScript EditorJavaScript Verifier     Perl Tutorials