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

So I'm writing a set of perl modules which will be used for both cli and web tools (Mason). My one problem right now is that I'm trying to figure out the best way to load either Carp or CGI::Carp at runtime depending on the environment. I've tried using require/import inside of a BEGIN block, but Carp doesn't have an import; it only seems to load properly with use.

Does anyone have an elegant way to load to approprate module?

-Aaron

Replies are listed 'Best First'.
Re: using Carp & CGI::Carp?
by chromatic (Archbishop) on Mar 24, 2003 at 18:21 UTC

    Which version of Carp are you using? I've just looked in 5.5.3, 5.6.0, and 5.8.0 and all three use Exporter, so they'll inherit import(). It was slightly broken in 5.6.0 (with lots of error messages from Carp::Heavy), so you might be running afoul of something else.

    Personally, I'd use require and import inside of a BEGIN, just as you describe. Can you post some test code?

      I don't have the old code handy anymore and of course when I try it now it works. Anyways, for the curious, this is what I'm using now:
      # test to see if we're running under Apache/mod_perl and load # the appropriate Carp module BEGIN { if ($ENV{MOD_PERL}) { require CGI::Carp; import CGI::Carp qw(carp confess cluck croak fatalsToBrowser); } else { require Carp; import Carp qw(carp confess cluck croak); } }

      -Aaron

        The indirect object syntax in the import call trips my paranoid-o-meter. If this is appropriately near the beginning of the program, you're probably okay, but it's fraught with enough peril (or, I can never remember all of the rules when it is and isn't okay) that I'd rather write:

        BEGIN { my @symbols = qw( carp confess cluck croak fatalsToBrowser ); if ($ENV{MOD_PERL}) { require CGI::Carp; CGI::Carp->import( @symbols, 'fatalsToBrowser' ); } else { require Carp; Carp->import( @symbols ); } }
Re: using Carp & CGI::Carp?
by jasonk (Parson) on Mar 24, 2003 at 17:18 UTC

    How about:

    if($web_based) { eval "use CGI::Carp;"; } else { eval "use Carp;"; } if($@) { die $@; }

    We're not surrounded, we're in a target-rich environment!
Re: using Carp & CGI::Carp?
by Zaxo (Archbishop) on Mar 24, 2003 at 23:26 UTC

    use if ... ;

    After Compline,
    Zaxo