XAMPP服务器上的Perl给出错误500



我对perl很陌生,我试图建立一个运行perl的web服务器…

我确实使它与另一个脚本工作,但与这个我得到了这个错误:

服务器错误!

服务器遇到内部错误,无法完成你的要求。

错误信息:End of script output before headers: index.pl

如果您认为这是服务器错误,请联系网站管理员。

错误500

localhost Apache/2.4.9 (Win32) OpenSSL/1.0.1g PHP/5.5.11

这是我的脚本:

#!"C:xamppperlbinperl.exe"
use strict;
use warnings;
#Open file and define $pcontent as content of body.txt
open(FILE,"body.txt"); 
local $/;
my $pcontent = <FILE>;
close(FILE)
#Open file and define $ptitle as content of title.txt
open(FILE,"title.txt"); 
local $/;
my $ptitle = <FILE>;
close(FILE)
#open html code
print "Content-type: text/htmlnn"; 
print "<html>";
#set html page title
print "<head>";
print "<title>$ptitle</title>";
print "</head>";
print "<body>";
#set the <body> of the html page
if ($pcontent = ""){
 print "
 <H1>ERROR OCCURED!</h1>"
} else{
print $pcontent;
};
#close the html code
print "</body>";
print "</html>";

它不工作的原因是因为您的Perl代码有语法错误,这阻止了它的编译。可以通过运行

检查代码中的语法错误
perl -c yourscript.pl

如果我们这样做,我们会发现:

syntax error at yourscript.pl line 11, near ")

如果我们看一下第11行,我们看到前面的行在语句末尾缺少一个分号。

close(FILE)     # <--- need semicolon here.

但是这个脚本还有一些其他的问题:

  • 您应该避免使用全局文件句柄(FILE),而使用词法文件句柄。一个优点是,由于它们在作用域结束时自动销毁(假设没有引用),它们将自动为您close d。
  • 您应该使用open的三参数形式,这将帮助您捕获某些错误
  • 你应该检查你的open成功,并报告一个错误,如果它不
  • 你应该只在一个小块内local调整$/的大小,否则它会影响你程序中你可能不想要的其他东西
  • 如果这个脚本不是一个简单的例子,你应该使用一个模板系统,而不是print一堆HTML。你的条件是错误的;您需要使用eq运算符来表示字符串相等,或者使用==来表示数值相等。=操作符用于赋值。

把所有这些放在一起,我将这样写:

use strict;
use warnings;
#Open file and define $pcontent as content of body.txt
my $pcontent = do {
    open my $fh, '<', 'body.txt' or die "Can not open body.txt: $!";
    local $/;
    <$fh>;
};
#Open file and define $ptitle as content of title.txt
my $ptitle = do {
    open my $fh, '<', 'title.txt' or die "Can not open title.txt: $!";
    local $/;
    <$fh>;
};
#open html code
print "Content-type: text/htmlnn"; 
print "<html>";
#set html page title
print "<head>";
print "<title>$ptitle</title>";
print "</head>";
print "<body>";
#set the <body> of the html page
if ($pcontent eq ""){
    print "<H1>ERROR OCCURED!</h1>"
} else{
    print $pcontent;
};
#close the html code
print "</body>";
print "</html>";

相关内容

最新更新