http://qs321.pair.com?node_id=586344


in reply to Re: Why am I getting "premature end of script header"?
in thread Why am I getting "premature end of script header"?

Thanks very much... I appreciate your help. So the following would be a fine way to test if a module is available and either use it or not use it accordingly?
print "Content-type: text/html\n\n"; print "here we go again..."; &a; sub a { BEGIN { eval ("use fakemodule;"); if ($@) { print "error happened $@"; } else { print "error didnt happen, do some stuff"; } } }

Replies are listed 'Best First'.
Re^3: Why am I getting "premature end of script header"?
by ikegami (Patriarch) on Nov 27, 2006 at 22:31 UTC

    My solution already does exactly that. Just replace the body of if ($@) with whatever you want.

    What you have there is the same as

    eval ("use fakemodule;"); if ($@) { print "error happened $@"; } else { print "error didnt happen, do some stuff"; } print "Content-type: text/html\n\n"; print "here we go again..."; &a; sub a {}
      thanks... so the BEGIN blocks should be at the beginning of the script... since i am using lots of calls to lwp, etc, i suppose something like the following would be a good idea:
      BEGIN { eval (" use LWP::UserAgent; use HTTP::Request::Common; "); if ($@) { $lwpavailable = 0; } else { $lwpavailable = 1; } }
      and then when I want to use it just test for that variable?
        BEGIN doesn't need to be at the beginning of the script, but it will make it easier for you to to follow the execution if it is.

        If you want to keep a variable to track whether the module is loaded you should use our, as you should always use strict (and warnings).

        use strict; use warnings; our $lwpavailable = 0; BEGIN { eval (" use LWP::UserAgent; use HTTP::Request::Common; "); if ($@) { $lwpavailable = 0; } else { $lwpavailable = 1; } }
        Yup, that would work great. Just add my $lwpavailable; before BEGIN.