[Canberra-pm] how to tell if a library is available?
Jacinta Richardson
jarich at perltraining.com.au
Sat Jun 14 02:40:16 PDT 2008
Kim Holburn wrote:
> I have a script which could use a library (Text::Autoformat) if it's
> available in the current libs or if it's in the directory the script
> is in. I'd like a simple test to tell this before I either try and
> use it or use a work-around.
>
> Is there any simple test for this?
Try using it with a string eval and then check $@. For example:
eval "use Foo;";
if($@) {
print "Could not find Foo\n";
}
eval "use Bar;";
if($@) {
print "Could not find Bar: $@\n";
}
print "Program completed\n";
with Foo.pm being:
package Foo;
print "Foo!\n";
1;
yields:
jarich at teddybear:/tmp$ perl test.pl
Foo!
Could not find Bar: Can't locate Bar.pm in @INC (@INC contains:
/etc/perl /usr/local/lib/perl/5.8.8 /usr/local/share/perl/5.8.8
/usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.8
/usr/share/perl/5.8 /usr/local/lib/site_perl
/usr/local/lib/perl/5.8.4 /usr/local/share/perl/5.8.4 .) at
(eval 2) line 1.
BEGIN failed--compilation aborted at (eval 2) line 1.
Program completed
If you choose to try to use a second module upon failing the first,
remember to save $@ if you ever intend to use it:
eval "use Foo;";
if(my $E = $@) {
print "Could not find Foo, trying Bar\n";
eval "use Bar;";
# $@ has now changed!
}
I hope this helps.
J
More information about the Canberra-pm
mailing list