yoda54 has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I'm writing a general utility script with multi functions like the one below. My questions is when I run this on a system that is missing certian modules the script bombs. How can I avoid this behavior? I would like a script to continue doing whatever it can without it exiting. As always Thanks!!

#!/usr/bin/perl use Getopt::Long; GetOptions("tk" => \$tk); if ($tk) { &tk(); } do this do whatever.... blah more blah sub tk { use Tk; use strict; more blah blah and yet more blah }

Edited by Chady -- moved text outside of code tags.

Replies are listed 'Best First'.
Re: How to keep a script from bombing due to a missing module?
by Nkuvu (Priest) on May 22, 2004 at 05:38 UTC
    Read perldoc -f eval. But here's a sample:

    #!/usr/bin/perl use strict; eval { require foo::bar }; # errors stored into $@ warn $@ if $@; # also, you can set a flag to see if the module # was available: my $use_foo_bar = 1 unless $@; print "I'm still going...\n"; if ($use_foo_bar) { foo::bar::function(); } else { print "No foo for you\n"; }
Re: How to keep a script from bombing due to a missing module?
by saintmike (Vicar) on May 22, 2004 at 05:42 UTC
    With eval and require you can check if a certain module is available or not. If it is, you can use it, if it isn't, you may decide on going an alternative path at runtime, like this:
    eval { require SomeModule; }; if($@) { print "SomeModule not found, doing something else\n"; } else { SomeModule->do_something; }
Re: How to keep a script from bombing due to a missing module?
by bobn (Chaplain) on May 22, 2004 at 19:09 UTC
    To do a 'use', you must evall within quotes, as in:
    #!/usr/bin/perl BEGIN { eval "use nosuchmodule;"; if ($@) { print "'use' failed\n"; } else { print "'use' ok\n"; } }

    --Bob Niederman, http://bob-n.com

    All code given here is UNTESTED unless otherwise stated.