in reply to How to conditionally use CGI::Carp?

From the documentation for use:

Imports some semantics into the current package from the named module, generally by aliasing certain subroutine or variable names into your package. It is exactly equivalent to

BEGIN { require Module; import Module LIST; }

except that Module must be a bareword.

So, given that, we can replace the 'use' with some form of logic structure

BEGIN { if ( ... ) { # require 'CGI::Carp'; require CGI::Carp; CGI::Carp->import('fatalsToBrowser'); } }

alternately, you can place the 'use' within an eval. (but you'll want it inside a BEGIN block, so it runs really early)

As for what to test for, to compare if you're under CGI vs. on a console... I typically test for the existance of $ENV{'SERVER'} or any of the other environmental variables that are set by the webserver when it's running under CGI.

Update: blah...no quotes in require when not giving direct paths to files.

Replies are listed 'Best First'.
Re^2: How to conditionally use CGI::Carp?
by argv (Pilgrim) on May 06, 2005 at 03:57 UTC
    You said to use:

    BEGIN { if ( ... ) { require 'CGI::Carp'; CGI::Carp->import('fatalsToBrowser'); } }

    But my perl doesn't like the single quotes. And, since I want to import more than one function, I used "import" directly, resulting in:

    require CGI::Carp; import CGI::Carp qw(fatalsToBrowser set_message carpout); set_message(\&handle_error);

    Next, you said:

    I typically test for the existance of $ENV{'SERVER'} or any of the other environmental variables

    Problem is, $ENV is completely empty when I run either from the tty or as a cgi. This surprises me, too, frankly. I test for anything, and always get zilch.

      OK, now waitaminute.... I've got an update, and hence a modification to my previous reply to this. That is, I said that my %ENV had nothing in it. I was wrong--it DOES. The reason I was mistaken is because I was trying to be tricky. Follow me on this because it gets circuitous--thus, interesting. I used the following code:

      my $ip = $ENV{'REMOTE_ADDR'}; BEGIN { if ( $ip ) { [...] } }

      That didn't work, which is no surprise, because the BEGIN block runs before the code runs, so $ip has no value when the BEGIN block runs. But, if that's the case, why does a print statement print? I take up this question in What is the scope of BEGIN? Or... when does it "begin?"..