PDA

View Full Version : how to use a perl module optionally (if available)?


perl_learner_01
09-12-2007, 06:05 AM
Hi Perl Gurus,

I want to use a perl module if it is present in my environment, otherwise ignore silently. I am doing something like:

eval "use Path::To::FooModule::Foo";
if( !$@ ) {
Path::To::FooModule::Foo::doSomething();
} else {
# ignore silently
}

problem with this code is that, it dumps a huge error message when "Foo" module cannot be located in the INC path. Is there a way to suppress all the error and warning messages due to missing Foo module?

Thanks in advance for your help!

FishMonger
09-12-2007, 06:47 AM
I have not tested this, but give it a try.

BEGIN {
eval { require Path::To::FooModule::Foo; };
Path::To::FooModule::Foo::doSomething() if !$@;
}

perl_learner_01
09-12-2007, 06:56 AM
That did it!!! Thanks a lot for your help!

FishMonger
09-12-2007, 06:56 AM
Here's a test i just ran and it's output.
use strict;
use warnings;
use Data::Dumper;

our $cgi;
BEGIN {
eval { require CGI; };
$cgi = CGI->new if !$@;
}
print Dumper $cgi;

BEGIN {
eval { require Path::To::FooModule::Foo; };
Path::To::FooModule::Foo::doSomething() if !$@;
}
print "\nDid we ignore silently?\n\n";


[root@perlman ~]# ./test.pl
$VAR1 = bless( {
'.parameters' => [],
'use_tempfile' => 1,
'.charset' => 'ISO-8859-1',
'.fieldnames' => {},
'escape' => 1
}, 'CGI' );

Did we ignore silently?

dandv
03-31-2009, 12:22 AM
I have not tested this, but give it a try.

BEGIN {
eval { require Path::To::FooModule::Foo; };
Path::To::FooModule::Foo::doSomething() if !$@;
}


There's a pitfall with that. To quote from The Perl Foundation on Exception Handling (http://www.perlfoundation.org/perl5/index.cgi?exception_handling):

This method is essentially non-atomic and has proven finicky. The problem lies with using $@. As it is global and there are many things which can reset it, either intentionally or otherwise, between the eval block failing and when it is checked.

The correct code would be:

eval { require Path::To::FooModule::Foo; 1; } and do {
Path::To::FooModule::Foo::doSomething() if !$@;
}