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

I want to wrap the require statement of specific "non-standard" library modules in eval{} to test if they are installed but not die if they are not. I only want to print to STDOUT if the module does not exist and continue on. I have tried doing this and testing for data in $@ but this does not seem to work. ANy ideas?

Replies are listed 'Best First'.
Re: eval {require module};?
by ikegami (Patriarch) on Apr 01, 2005 at 23:24 UTC

    Weird, works for me:

    >perl -e "eval { require Boo }; print """[$@]""" if $@;" [Can't locate Boo.pm in @INC (@INC contains: ...) at -e line 1. ]

    Remember that require doesn't call import like use does, so you need to call it explicitly:

    use Module; | v require Module; Module->import() if Module->can('import'); use Module qw(a b); | v require Module; Module->import(qw(a b)) if Module->can('import'); use Module (); | v require Module;
Re: eval {require module};?
by BUU (Prior) on Apr 01, 2005 at 23:18 UTC
    You need to use the string form of eval:
    eval "use MyModule;"
    Then you can test $@ as normal. Not entirely sure why.
Re: eval {require module};?
by nobull (Friar) on Apr 02, 2005 at 04:17 UTC
    There are some situations (which I do not fully understand) where eval{} can trap an error and yet fail to set $@. However the return value will be undef.

    So...

    unless( eval { require module; 1 } ) { my $err = $@ || 'eval failed but did not return error'; # do something with $err }
    Update: instert missing 1.
      Many months later I now know how eval{} can fail and yet not set $@. It happens if a DESTROY method called during the stack-unwind also does an eval.
      use AtExit; eval { my $q = AtExit->new(sub{eval{}}); die "Oops\n"; }; print $@; # Prints nothing
        Which means you have to
        sub DESTROY{ local $@; eval{...} }
        if you want to use eval in DESTROY.
Re: eval {require module};?
by tlm (Prior) on Apr 01, 2005 at 23:27 UTC

    Try:

    eval { require Foobar } or die "Where's Foobar? ($@)\n";

    the lowliest monk