What should you call after printing HTML from a Perl CGI script? I have seen empty return
statements, exit
statements, and in some cases nothing at all. Does it matter?
#!perl
print "Content-type: text/html\n\n";
print <<'END_HTML';
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello world!</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
END_HTML
# do anything else here?
# return;
# exit;
Let's suppose you have some tests where you are printing HTML that isn't at the very end of the file. In this case is it more clear to call exit or return to visually show that the script should end at that time? I know this isn't the best way to write this--please just take this at face value for the sake of the question.
#!perl
use CGI;
my $q = CGI->new();
my $action = $q->param('action');
my $html_start = "Content-type: text/html\n\n";
$html_start .= <<'END_HTML';
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello world!</title>
</head>
<body>
END_HTML
my $html_end = <<'END_HTML';
</body>
</html>
END_HTML
if ($action eq 'foo') {
print $html_start;
print '<p>foo</p>';
print $html_end;
# do anything else here?
}
else {
print $html_start;
print '<p>bar</p>';
print $html_end;
# do anything else here?
}
You should always print out "\n\n" at the end of your output to tell the webserver the output is finished. Apache may do this for you on successful script termination.
If your script is finished, you should technically call "exit" with the appropriate exit status-- zero for success, nonzero for errors. The webserver inspects the exit status and renders the appropriate page (error code 500 is typical if the exit status shows anything other than success). If you don't specify a "return" value or call exit directly, Perl (in this case) will assume successful termination and the webserver will treat your CGI script the same as if you called "exit(0)".
This is all described in the CGI specification (RFC 3875 is current, IIRC).
I guess this is more a question about coding style than functionality. If you have a simple, straightforward program, with no branching, there is little reason to mark the termination of the program by anything special:
However, if the structure is more complex, I would advise to mark the termination point by something specific, to signal to someone who reads your code that, for that defined set of conditions, there is nothing to take into account there anymore.
I would use exit rather than return, for the simple reason that return can be mistaken for the end of a sub, whereas exit very specifically states that the program terminates at this point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With