【问题标题】:Is there anything wrong with using requires after output starts printing?输出开始打印后使用 requires 有什么问题吗?
【发布时间】:2010-02-01 17:58:59
【问题描述】:

例子:

my $page = $args{'p'};
exit 1 if $page =~ /[^\d\w]/;

print "Content-Type: text/html\n\n";

print "<html><head></head><body>";

require "$page.pl";

somefunc();

print "</body></html>";

在输出开始后使用 require 有什么问题吗?或者所有 requires 都应该在脚本的顶部?

【问题讨论】:

  • 没什么问题,除了使用require "file"; 重用代码通常有什么问题。

标签: perl


【解决方案1】:

我不认为这有什么问题。

但是,如果您希望或需要脚本中的更多一致性,您可以将所需脚本中的代码重写为子例程。例如:

##### old page.pl ######
print "This is the body.<P>\n";
1;

##### old cgi script #####
print "Content-type: text/html\n\n";
print "<html><head></head><body>\n";
require "page.pl";


##### new page.pl ######
sub page_body {
    print "This is the body.<P>\n";
}
1;

##### new cgi script #####
require "page.pl";                    # now at the top of script
print "Content-type: text/html\n\n";
print "<html><head></head><body>\n";
&page_body;

【讨论】:

  • 事实上,重构旧的单体 cgi 脚本(带有内联 HTML,没有函数等)的第一步是将功能划分为单独的文件并使用 require
【解决方案2】:

不,不需要所有requires 都在顶部。但是,如果 require 失败,您的 HTML 将已经发送到一半。 :-P

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 2018-02-19
    • 1970-01-01
    相关资源
    最近更新 更多