1

Possible Duplicate:
How can I check if I have a Perl module before using it?

I'd like to eval a use statement similar to this: eval {use $foo;} but am having trouble with the correct syntax. I've tried various combinations of string interpolation, but the eval always succeeds even for a module that does not exist. Can someone give me hand with this one?

Community
  • 1
  • 1
Lazloman
  • 1,289
  • 5
  • 25
  • 50
  • 2
    I'm not sure how `eval` is succeeding; I get a syntax error when using a variable with `use`. From `perldoc -f use`: "[use Module LIST] is exactly equivalent to BEGIN { require Module; import Module LIST; } except that Module *must* be a bare word." – chepner Feb 07 '12 at 15:41
  • Define "eval always succeeds". – TLP Feb 07 '12 at 15:41

2 Answers2

7

The idiom you are looking for is:

eval "use $module; 1" or ... ;

eval "use $module; 1" or warn "$module is not available: $@";
eval "use $module; 1" or die "This script requires $module";
eval "use $module; 1" or $module_available = 0;

eval "always succeeds" in the sense that program execution will continue no matter what code is evaluated -- that's really the whole point of an eval statement. If the evaluated string contained errors -- run time or compile time -- the return value of the eval call is undef and the special variable $@ will be set with an appropriate error message.

The use statement, even when successful, does not return a value. That's why this idiom includes the "; 1" at the end.

mob
  • 117,087
  • 18
  • 149
  • 283
0

use is a keyword that is processed during compilation, as is mentioned in the comments, it does require you to use bareword arguments. That is, no variables.

Now, I can't get an eval { use $foo } to even compile, because it causes a syntax error, so the script is never run. I'm not sure what you mean exactly by "always succeeds", unless you mean the opposite: "always fails".

TLP
  • 66,756
  • 10
  • 92
  • 149