Darxus on Fri, 25 Aug 2000 13:41:46 -0400 (EDT)


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

conditionally loading modules


This is bothering me, and I feel like telling somebody about it.

I still consider myself relatively new at perl, but in each of the 3
programs I've written that I felt were worth posting to freshmeat, I've
used a module that is not part of the default perl install.  Because the
module is not on all systems, and because the program could still do
useful things without the module, I want to test for its presence, and
load it if I can, and deal if I can't.

Perl does not seem to like this idea very much.  That's what's bothering
me.

Beyond the possibility that I may have just overlooked something, there is
the fact that when I was looking very actively, I found it very hard to
find information on this subject.

Sure, you can do 

$gnupg = eval "require 'GnuPG.pm';"

And then check $gnupg before attempting anything gpg related.  I'm fine
with that.  It's a little odd, and I don't think particularly well
documented, but somebody (Kyle) showed me how to do it, and I can use it.

The problem comes with stuff like Date::Calc.  If you require() it, it
doesn't import its functions, and it gives you errors saying that its
functions aren't defined when you try to use them.

The answer I've come up with is this:

if (eval "require Date::Calc;")
{
  import Date::Calc;
  $dow = 1;
} else {
  print STDERR "Connot find Perl module Date::Calc, not generating Day Of Week stats.\n";
  $dow = 0;
}

The significant part is the import().  It took reading its section of the
perlfunc man page quite a few times, and a lot of trial and error to make
it work.  The fact that perl seems to not bother reporting errors for
these things didn't help.

It seems to me that at some point in writing a program, every coder should
sit back and think "hmm, what modules that I'm using could this program
function without ?", and then load them conditionally, and deal with their
absence.  This should be a common coding practice, and well documented.


I feel like I should mention that the only perl book I've gotten around to
picking up is the blue camel.
-- 
www.ChaosReigns.com
**Majordomo list services provided by PANIX <URL:http://www.panix.com>**
**To Unsubscribe, send "unsubscribe phl" to majordomo@lists.pm.org**