在自定义perl模块中发生错误以读取文件。这使用CGI,因此错误消息将显示在浏览器中。
my $check = CreateExam->new("exam2.txt","grades.txt");
$check->readexam();
CreateExam.pm:
sub new {
my ($class,$file,$grades) = @_;
print "<p>in new: file: $file, grades: $grades</p>\n";
return bless {'file'=>$file,'gradefile'=>$grades},$class;
}
sub readexam {
my $self = shift;
print "<p>in readexam File: $self->{'file'}</p>\n";
if (defined($self->{'file'})) {
my $self->{'questions'} = [];
my $count = -1;
my $file = $self->{'file'};
open(my $handle,"<$file") or die "<p>it was the open. File: $file</p>";
while(<$handle>) {
输出中:
in new: file: exam2.txt, grades: grades.txt
in readexam File: exam2.txt
Use of uninitialized value $file in concatenation (.) or string at /var/www/homeworks/hw10/CreateExam.pm line 35 (#1)
Software error:
<p>it was the open. File: </p> at /var/www/homeworks/hw10/CreateExam.pm line 35.
Software error:
[Sun Dec 21 14:30:31 2014] hw10.cgi: <p>it was the open. File: </p> at /var/www/homeworks/hw10/CreateExam.pm line
[Sun Dec 21 14:30:31 2014] hw10.cgi: [Sun Dec 21 14:30:31 2014] hw10.cgi:
it was the open. File:
at /var/www/homeworks/hw10/CreateExam.pm line 35.
我有use warnings
和use diagnostics
。我两次收到错误消息的一部分似乎很奇怪。
答案 0 :(得分:4)
您在代码中创建了一个新变量$self
:
my $self->{'questions'} = [];
my $count = -1;
my $file = $self->{'file'};
然后,您尝试访问它并将值分配给另一个变量$file
,这将变为未定义。使用my
时,在当前范围内创建新变量。
所以答案可能是:在这种情况下不要使用my
。你已经在子的顶部使用了一次。
...然而
将新数组引用分配给键questions
完全是多余的。 Perl的自动修复可以处理这种情况,例如:如果你push @{ $self->{questions} }, $foo
,你将创建一个数组引用。