in reply to Re: Test that a module is installed
in thread Test that a module is installed
Merlyn's answer packs a lot into a short paragraph. Let's unpack it a bit. Compare these:
eval { use Bundle::Catalyst }; eval " use Bundle::Catalyst ";
The BLOCK version (top) is compiled when the program is compiled, but "use" creates an immediate BEGIN block which executes right away. If the module can't be found, the compilation fails and the program is never run. The string version (bottom) is compiled and executed during run-time and any error is caught by the eval.
If an error is caught, eval returns undef. But what if an error isn't caught? Because "use" is equivalent to a BEGIN block, it executes during compilation of the string, and then there is nothing left that happens during execution of the string, so eval also returns undef in that case. That's OK, as long as you test the error condition, not the result of the eval. Compare these:
# check eval ok( eval " use Bundle::Catalyst ", "trying Bundle::Catalyst" ); # check error condition eval " use Bundle::Catalyst "; my $err = $@; is( $err, undef, "trying Bundle::Catalyst" );
The first version will never be true, even if the module is found, because eval is always returning undef. The second version will work, because you're checking for the error condition.
Another alternative is "require" -- which happens at runtime and returns the last value of the last statement in the module (which is why .pm files almost always end with "1;" to ensure they return a true value). (Though note that "require" does not run "import" the way that "use" does.) Consider these:
eval " use Bundle::Catalyst "; eval " require Bundle::Catalyst ";
Because the second one returns undef if the module isn't found or returns true if the module is found (and written correctly to return true), you can use that version with "ok" if you want and you can even use it in BLOCK form:
# both work ok( eval " require Bundle::Catalyst ", "trying Bundle::Catalyst" ); ok( eval { require Bundle::Catalyst }, "trying Bundle::Catalyst" );
That said, if you're trying to test that a module is found in a test script, you are best off using use_ok or require_ok as those handle all this complexity for you.
-xdg
Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.
|
|---|