perl:无法在对象中打印到文件句柄?

时间:2015-01-13 21:38:56

标签: perl cgi

我正在尝试调试报告没有错误的cgi脚本,但浏览器显示生成的文本而不是呈现页面。我从一个容器对象(各种)中调用cgi来查看我是否发送了两次头文件。

package debugcgi;

use CGI qw(:standard);
use CGI qw(:standard Vars);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);

sub new {
    my ($class,$glob) = @_;
    open(lls,">process-cgi.txt");
    return bless{'cgi'=>CGI->new($glob),'glob'=>\*lls,'headers'=>0},$class;
}

sub header {
    my $self = shift;
    my $tmp = shift->{'cgi'}->header(@_);
    print $tmp;
    my $t = $self->{'glob'};
    print $t $tmp;
    $self->{'headers'}++;
}
...

sub myclose {
    my $self = shift;
    my $t = $self->{'glob'};
    my $tmp = $self->{'headers'};
    print $t "\nnumber of headers: ";
    print $t $tmp;
    close $t;
}

1;

用作坏脚本中真实cgi的简单替换:

use debugcgi;
...
#my $cgi = CGI->new(\*STDIN);
my $cgi = debugcgi->new(\*STDIN);
... 
print $cgi->header(Referer => $cgi->url());

哦。

但是除了“标题数:0”之外没有任何内容打印到文件中,我仍然会显示一个完整的HTML文档。我做错了什么,我怎么能改进呢?

1 个答案:

答案 0 :(得分:1)

你有问题:

sub header {
    my $self = shift;
    my $tmp = shift->{'cgi'}->header(@_);
    ...

$ self是你的哈希,它包含cgi对象。所以,你需要这样做:

sub header {
    my $self = shift;
    my $cgi = $self->{'cgi'};
    my $header_str = $cgi->header(@_);

<强>移
将数组的第一个值移开并返回它,将数组缩短1并将所有数据向下移动。

http://perldoc.perl.org/functions/shift.html

这更像是现代perl代码的样子:

DebugCGI.pm:

package DebugCGI;

use strict;
use warnings;
use 5.016;
use Data::Dumper;

use CGI; 
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);


sub new {
    my ($class, $PARAMFILE) = @_;

    my $fname = 'process-cgi.txt';

    open my $OUTFILE, '>', $fname
        or die "Couldn't read from $fname: $!";

    my $obj_attributes = {
        'cgi_obj' => CGI->new($PARAMFILE),
        'outfile' => $OUTFILE,
        'header_count' => 0,
    };

    return bless $obj_attributes, $class;

}

sub header {
    my ($self, @headers) = @_;

    my $cgi = $self->{'cgi_obj'};
    my $header_str = $cgi->header(@headers);
    print {$self->{outfile}} $header_str;

    $self->{'header_count'}++;

    return;
}

sub close {
    my ($self) = @_;

    my $count = $self->{'header_count'};
    my $OUTFILE = $self->{'outfile'};

    say {$OUTFILE} "number of headers: $count";
    close $OUTFILE;

    return;
}

1;

测试出来:

use strict;
use warnings;
use 5.016;
use Data::Dumper;

use DebugCGI;


my $fname = 'params.txt';

open my $PARAMFILE, '<', $fname
    or die "Couldn't open $fname: $!";

my $debug_cgi = DebugCGI->new($PARAMFILE);

close $PARAMFILE;

$debug_cgi->header(
    '-type' => 'text/html; charset=UTF-8',
);

$debug_cgi->header(
    '-type' => 'text/plain: charset=UTF-8',
);

$debug_cgi->close;

params.txt:

x=3
y=4

输出:

$ cat process-cgi.txt
Content-Type: text/html; charset=UTF-8

Content-Type: text/plain: charset=UTF-8

number of headers: 2

请注意$cgi->header()输出后添加的双重换行符。双换行符是浏览器的信号,标题已结束,任何后续文本都被视为响应的主体。因此,您不能print $cgi->header()两次,因为第二次文本不会被视为标题。如果由于某种原因您希望print $cgi->header()两次,那么您可以使用s/\s+\z//xms删除尾随换行符。