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

How can I stop my script executing without using die. If I die after printing some valid html it does not get displayed and I get a premature end of script headers error. Should I just use a goto to skip to the end of the file? I tried closing stdout and then die but I still get the premature headers error. For example
my $q= new CGI; print $q->header; print "error text"; #stop the script going any further die "something bad happened;
If I remove the die the html displays but the script keeps going. thanks in advance

Replies are listed 'Best First'.
Re: Exit CGI gracefully
by rob_au (Abbot) on Oct 02, 2002 at 13:46 UTC
    You are looking for the exit command - From the documentation for this function ...

    exit EXPR Evaluates EXPR and exits immediately with that value. Example: $ans = <STDIN>; exit 0 if $ans =~ /^[Xx]/; See also "die". If EXPR is omitted, exits with 0 status. The only universally recognized values for EXPR are 0 for success and 1 for error; other values are subject to interpretation depending on the environment in which the Perl program is run- ning. For example, exiting 69 (EX_UNAVAILABLE) from a sendmail incoming-mail filter will cause the mailer to return the item undelivered, but that's not true everywhere. Don't use "exit" to abort a subroutine if there's any chance that someone might want to trap what- ever error happened. Use "die" instead, which can be trapped by an "eval". The exit() function does not always exit immedi- ately. It calls any defined "END" routines first, but these "END" routines may not themselves abort the exit. Likewise any object destructors that need to be called are called before the real exit. If this is a problem, you can call "POSIX:_exit($status)" to avoid END and destructor processing. See perlmod for details.

     

    perl -e 'print+unpack("N",pack("B32","00000000000000000000000111000101")),"\n"'

Re: Exit CGI gracefully
by blaze (Friar) on Oct 02, 2002 at 15:10 UTC
    I normally call a sub, and exit from there, for instance if im checking for an empty string, id do something like
    if ($val eq ""){ &error; } sub error{ print <<ErrHtml <html> <head> <title>Error</title> </head> <body> An error occurred </body> </html> ErrHtml exit; #exit so the script stops here }

    hth,
    -Robert
Re: Exit CGI gracefully
by nutshell (Beadle) on Oct 02, 2002 at 17:19 UTC
    Are you just trying to catch CGI.pm errors? If so, use:
    use CGI; use CGI::Carp 'fatalsToBrowser'; my $q = new CGI; print $q->header; # ........
    --nutshell