Perl 缓冲输出
我正在更改现有解决方案中的一些 Perl 脚本。由于升级 (Windows) 服务器时发生了一些变化,我已将它们从运行 ISAPI 切换到 CGI。这意味着我现在必须手动发送 Content-Type,否则将会失败。
因此,我需要启用输出缓冲(打印语句,因此 STDOUT),发送 Content-Type: text/html,但在重定向的情况下,我需要清除输出缓冲区并发送新标头。
我该怎么做?
或者还有别的办法吗?请注意,该脚本已经使用 print
来输出 HTML,我无法更改它。 (写于20世纪90年代初。)
select(STDOUT);
$| = 0;
print "Content-Type: text/html\n\n";
# somehow clear output
print "Location: login.pl\n\n";
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\n\n";
# somehow clear output
print "Location: login.pl\n\n";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法“撤消”对 STDOUT 的
打印
。在将任何内容发送到 STDOUT 之前,您需要决定是生成 HTML 输出还是重定向。一种方法是
选择
内存缓冲区而不是 STDOUT:一旦您确定不会生成重定向,您就可以重新
选择< /code> STDOUT 并输出缓冲区:
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:As soon as you're sure you won't be generating a redirect, you can re-
select
STDOUT and output the buffer:最安全的(IMO)方法之一是在输出任何其他内容之前,将决定是否要重定向所需的所有逻辑放在脚本的顶部。
如果您根本不想更改原始脚本,请编写一个单独的脚本,该脚本仅执行重定向/内容类型逻辑,并在必要时调用您的原始脚本。
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.
尚未涵盖的一个答案是简单地将 STDOUT 默认句柄替换为 BEGIN 中的不同句柄,然后在 END 中处理它,如果没有标题,则添加
Content-Type: text/html\n\n
。丑陋,但理论上应该有用。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.