# The following was supposedly scribed by
# Sisyphus
# on Monday 22 March 2004 09:31 pm:

|use warnings;
|
|BEGIN {
|   eval{require Inline::C};
|   if($@) {
|     print "No Inline::C here\n";
|     # do whatever you want
|     exit;
|     }
|   }
|
|use Inline C => <<'EOC';
|
|void got_it() {
|      printf("We have Inline::C\n");
|      }
|
|EOC
|
|got_it();
|
|__END__
|
|Seems to work as you want. As it is it prints "We have Inline::C". If I
|change all occurrences of 'Inline::C' (and 'Inline C') to 'Inline::D'
|(and 'Inline D') then it prints "No Inline::D here" and quietly exits.

Sounds about right, except I think the OP wanted to do something besides exit 
if Inline::C is not available.  Usually, you would have a require() statement 
for this sort of thing, since those don't get caught at compile time (trouble 
with use() is that the interpreter wil find it anywhere.)

This won't work:
  require Inline C => <<'EOC';

So, you would have to call the import routine directly:

BEGIN {
   eval{require Inline::C};
   if($@) {
     print "No Inline::C here\n";
     # do whatever you want
     exit;
     }
   else {
     Inline::import(Inline, C => <<'EOC'
     void got_it() {
        printf("we have inline::C\n");
     }

     EOC
     );
     }

   }



Example:  you've written a function (or class) in both C and Perl, and the C 
one is faster, but you want the Pure Perl one to be available as a fallback.

You could also put the 'use Inline C => $code' line inside of an eval, or 
(maybe a better plan) write two modules and do an eval {require } on each in 
turn.  The one which contains 'use Inline::C' will fail the require, so you 
can fall-back on the pure-perl one in an else{} block.

Of course, as Rob has demonstrated, you need to do all of this fancy stuff in 
a BEGIN block.

--Eric


Reply via email to