Beefy Boxes and Bandwidth Generously Provided by pair Networks kudra
"be consistent"
 
PerlMonks  

How to keep a script from bombing due to a missing module?

by yoda54 (Monk)
on May 22, 2004 at 01:07 UTC ( [id://355548]=perlquestion: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.

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 01: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 01: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 15: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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://355548]
Approved by graff
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.