【问题标题】:Perl on XAMPP Server gives erorr 500XAMPP 服务器中的 Perl 给出错误 500
【发布时间】:2014-10-02 03:19:25
【问题描述】:

我对 perl 很陌生,我正在尝试设置一个运行 perl 的 Web 服务器...

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

服务器错误!

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

错误信息:头文件前的脚本输出结束:index.pl

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

错误 500

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

这是我的脚本:

#!"C:\xampp\perl\bin\perl.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/html\n\n"; 
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>";

【问题讨论】:

    标签: apache perl xampp


    【解决方案1】:

    它不起作用的原因是您的 Perl 代码存在语法错误,导致无法编译。您可以通过运行

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

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

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

    如果我们查看第 11 行,我们会发现之前的行在语句末尾缺少一个分号。

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

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

    • 您应该避免使用全局文件句柄 (FILE),而应使用词法文件句柄。一个优点是,由于它们在其作用域结束时自动销毁(假设没有引用),它们将自动为您提供closed。
    • 您应该使用open 的三参数形式,这将帮助您捕获某些错误
    • 您应该检查您的open 是否成功,如果不成功则报告错误
    • 你应该只在一个小块内localize $/,否则它会影响你程序中你可能不希望它发生的其他事情
    • 如果这个脚本变得不是一个简单的例子,你应该使用模板系统而不是 printing 一堆 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/html\n\n"; 
    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>";
    

    【讨论】:

    • 当然都是好的建议。但是,您如何看待推荐autodie 而不是建议初学者包含手动or die 语句?在我看来,懒惰无处不在,因此 autodie 不仅会自动处理错误消息,而且它还包含比我们经常看到的不可避免的 or die $! 更多的信息。
    • autodie 也是一个不错的选择。不过,我喜欢确保人们在给他们捷径之前了解发生了什么。 :)
    猜你喜欢
    • 2017-12-30
    • 2018-08-19
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多