Test for available modules in Perl

As I mentioned earlier the difference between use and require is that the second is evaluated only at execution time, making it possible to test if a given module was imported successfully. One possible use for this is to make your script deployable on multiple machines where you might or might not have the option to install modules from CPAN/PPM.

Below you can see an example for finding the YAML library in multiple possible places and then aliasing it to a variable, so that it can be referred to in an unique way ($yaml_dump-($stuff)), not matter from which library it got imported:

#try to determine the installed YAML library
my $yaml_dump;
eval {
 require Module::Build::YAML;
 $yaml_dump = &Module::Build::YAML::Dump;
eval {
 require PPM::YAML;
 $yaml_dump = &PPM::YAML::serialize;
} unless ($yaml_dump);
eval {
 require YAML;
 $yaml_dump = &YAML::Dump;
} unless ($yaml_dump);
die("Failed to locate the YAML library!n") unless ($yaml_dump); 

Leave a Reply

Your email address will not be published. Required fields are marked *