开发者

Perl buffered output

I'm changing some Perl scripts in an existing solution. Due to some changes when upgrading the (Windows) server I've switched them from running ISAPI to CGI. This means I now have to send Content-Type manually or it will fail.

So I need to enable output buffering (print statements, so STDOUT), send Content-Type: text/html, but in the cases where it is a redirect I need to clear output buffer and send new header.

How do I do that?

Or is there another way? Note that the script is already using print for outputting HTML, and I can't change that. (It was written in the early 90's.)

select(STDOUT);
$| = 0;
print "Content-Type: text/html开发者_StackOverflow社区\n\n";
# somehow clear output
print "Location: login.pl\n\n";


You can't "undo" a print to STDOUT. You need to decide whether you're generating HTML output or a redirect before you send anything to STDOUT.

One way of doing that would be to select an in-memory buffer instead of STDOUT:

my $buffer = '';
open(my $out, '>', \$buffer) or die;
select($out);
print "Content-Type: text/html\n\n";

if (generate_redirect) {
  print STDOUT "Location: login.pl\n\n";
} else {
  print STDOUT $buffer;
}

As soon as you're sure you won't be generating a redirect, you can re-select STDOUT and output the buffer:

select STDOUT;
print $buffer;
print "<p>HTML now goes to client instead of \$buffer</p>\n";


One of the safest (IMO) ways of doing this is to put all the logic you need to decide whether you want to redirect or not at the top of your script, before you output anything else.

If you don't want to change the original script at all, write a separate script that just does the redirection/content-type logic and calls your original script afterwards if/when necessary.


One answer that hasn't been covered is simply replacing STDOUT default handle to a different handle in BEGIN, then processing it in END adding Content-Type: text/html\n\n if there is no header. Ugly, but should work ... in theory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜