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

Dear Monks, I need a script to continue running even if a module is not installed. I done a bit a reading and searching but I am still unable to find a solution for this. I would imagine the script should look something like this? Any advice on this is greatly appreciated. Thanks
#!/usr/bin/perl -w # $module is the module you're checking for $module = "DBI"; eval("require $module") ? &run() : &runwithout; sub run { print "Installed\n"; use DBI; } sub runwithout { print "Not Installed\n"; }

20030710 Edit by Corion: Added CODE tags

Replies are listed 'Best First'.
Re: Running a script if module is not installed
by sgifford (Prior) on Jul 10, 2003 at 16:50 UTC
    You're basically right; you just want to wrap the use part in an eval block. You don't have to use a string, and not using a string will be a little bit faster. Something like:
    #!/usr/bin/perl -w use strict; eval "use DBI"; if ($@) { runwithout(); } else { run(); }

    Update: Looks like you do need to use a string to get the effect you want. Above code has been updated. Also added use strict

Re: Running a script if module is not installed
by tall_man (Parson) on Jul 10, 2003 at 16:51 UTC
    See the Perl Cookbook, section 12.2 "Trapping Errors in require or use". The eval of the require is good, but then you could just run import for the module if it works (also make sure to run in a BEGIN block).
    BEGIN { my $mod = "DBI"; if (eval "require $mod") { $mod->import(); # Set flags, etc. } else { # Set flags, etc. here. } }
Re: Running a script if module is not installed.
by roju (Friar) on Jul 10, 2003 at 20:54 UTC
    I'm not sure why that doesn't work. I will recommened against using the & notation if at all possible. The following works for me (cygwin 5.8).

    $foo=5; sub has {print "ok\n"} sub hasnt {print "no dice\n"} eval "require $foo" ? has : hasnt

    prints ok

    $foo="nosuchmodule"; sub has {print "ok\n"} sub hasnt {print "no dice\n"} eval "require $foo" ? has : hasnt

    prints no dice