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

Is there any way for a CGI script to check if DBI is available before trying to create a database handle? Code snippet would be appreciated

Replies are listed 'Best First'.
Re: Check if DBI is installed
by wog (Curate) on Sep 02, 2001 at 09:57 UTC
    You can check if DBI, or any other module, is available by trying to load it in an eval, and checking for an error (in $@):

    eval { require DBI; DBI->import; # ... as is documented in perlfunc under 'use', # this is same as 'use DBI', except done when the eval {} # is run, not when compiled (eval BLOCK catches only # runtime errors, eval STRING must be used to catch # errors that happen at compile time, but eval BLOCK # is almost always better.) }; if ($@) { # $@ has error from eval, if any. # Couldn't load DBI } else { my $dbh = DBI->connect(...); # Loaded DBI, okay. }
      autouse apparently has the same effect as require / import

      use warnings ; use strict; use autouse 'foo'; # perldoc autouse eval {foo::not_here();}; # perldoc -f eval my $we_care=0; warn $@ if ($@ && $we_care);
      Update: changed
       use autouse foo
      to
       use autouse 'foo' (thanks tachyon)

      --mandog
        C:\>type test.pl use warnings ; use strict; use autouse foo; # perldoc autouse eval {foo::not_here();}; # perldoc -f eval my $we_care=0; warn $@ if ($@ && $we_care); C:\>perl test.pl Bareword "foo" not allowed while "strict subs" in use at test.pl line +5. Execution of test.pl aborted due to compilation errors. C:\>type test.pl use warnings ; use strict; use autouse 'foo'; # perldoc autouse eval {foo::not_here();}; # perldoc -f eval my $we_care=0; warn $@ if ($@ && $we_care); C:\>perl test.pl C:\> C:\>type test.pl use warnings ; use strict; use autouse 'foo'; # perldoc autouse eval {foo::not_here();}; # perldoc -f eval warn $@ if $@; C:\>perl test.pl Undefined subroutine &foo::not_here called at test.pl line 6. C:\>

        I presume you mean something like the last example? cheers

        tachyon

        s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print