12.2. Trapping Errors in require or useProblemYou 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. Solution
Wrap the # no import BEGIN { unless (eval "require $mod") { warn "couldn't load $mod: $@"; } } # imports into current package BEGIN { unless (eval "use $mod") { warn "couldn't load $mod: $@"; } } 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
You don't want to use If you need to try several modules in succession, stopping at the first one that works, you could do something like this:
BEGIN {
my($found, @DBs, $mod);
$found = 0;
@DBs = qw(Giant::Eenie Giant::Meanie Mouse::Mynie Moe);
for $mod (@DBs) {
if (eval "require $mod") {
$mod->
We wrap the See Also
The
Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|