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

Hello monks,

I am trying to add some more helpful behavior to an existing script that is DBI dependent. On systems without DBI it complains about how DBI.pm is not found and so on.

Some of what it is supposed to do is not DBI dependend (basic stats gathering), what I want to do is run the non-DBI stuff anyway....
I thought I had it figured out, but... here is what I have tried. It still complains of no DBI module when there is none and refuses to run due to missing modules...

$use_dbi = 1; eval("use DBI;"); $use_dbi = 0 if (not($@); if ($use_dbi) { use DBI; ... } else { print "NO DBI\n"; } ... do other stuff ...
help?

jcpunk
all code is tested, and doesn't work so there :p (varient on common PM sig for my own ammusment)

Replies are listed 'Best First'.
Re: DBI detector?
by davidrw (Prior) on Apr 03, 2006 at 20:41 UTC
    first, you have to get rid of the use DBI; inside the if() statement -- that is being run at compile time (see use). For (attempting) loading at runtime, see require. Also I think your $@ logic is backwards (see eval)... Try something like this:
    eval "require DBI"; my $dbi_ok = $@ ? 0 : 1; if( $dbi_ok ){ # do DBI stuff here }else{ print "NO DBI\n"; }
      Bingo! I thank thee

      jcpunk
      all code is tested, and doesn't work so there :p (varient on common PM sig for my own ammusment)
      Why did you switch from eval "use DBI" to eval "require DBI"? Both occur at run-time here (since the eval is executed at run-time here), but require doesn't import the symbols that use would import.
        mostly cause require docs use the eval "require DBI" form as an example, and so i was pretty confident that would work w/o trying it, and the critical piece for OP was to remove the load-time 'use' call .. i also vauguely remember having problems once doing a eval "use Foo" once but really can't remember what (possibly {probably??} totally unrelated .. was a load order issue maybe??) .. so, in summary, no real good reason :)
Re: DBI detector?
by ikegami (Patriarch) on Apr 03, 2006 at 20:01 UTC

    Except for the extra/missing paren, some redundancy, your code looks fine to me. What's your exact error message? Maybe a DBI *driver* is missing, as opposed to DBI itself.

    my $use_dbi = eval ' use DBI; use DBD::mysql; 1 # or undef if the above fails. '; if ($use_dbi) { ... } else { print "NO DBI\n"; } ... do other stuff ...
      Error wise I get
      Can't locate DBI.pm in @INC (@INC contains: .....)  at DBIDetector.pl line 14

      jcpunk
      all code is tested, and doesn't work so there :p (varient on common PM sig for my own ammusment)
        Hum, there goes my theory. Could you show us your script, especially what's at and around line 14?