在字符串eq中使用未初始化的值$ end_time1 .......在perl中出错

时间:2014-09-15 07:04:41

标签: database perl null

我想从我的数据库中检索一些数据,如果$ end_time1为null则会更新表,否则什么都不做,但是当我运行代码时,我发现$ end_time1为null,那么将更新表,但如果不为null,它将返回错误:

Use of uninitialized value $end_time1 in string eq ........

我的部分代码:

my $select_sth = $dbh->prepare("SELECT id ,H1, H2, addr1, addr2, time_1, time_2,   
end_time_1,end_time_2,count1,count2 FROM service") or die "$dbh->errstr";
$select_sth->execute() or die "$dbh->errstr";
while (my @row_ref = $select_sth->fetchrow_array)
 {
    my $Rid = $row_ref[0];
    my $addr1 = $row_ref[3];
    my $addr2 = $row_ref[4];
    my $end_time1 = "NULL" unless $row_ref[7];
    my $end_time2 = "NULL" unless $row_ref[8];
    my $count1 = $row_ref[9];
    my $count2 = $row_ref[10];
    if($end_time1 eq "NULL")
     {
        print "$end_time1 is null\n";
        $dbh->do ("update service set end_time_1 = '$datetime_now' where id = $Rid");
     }
 }

请问某人我的代码有什么问题?如何解决?

2 个答案:

答案 0 :(得分:1)

如果未定义$endtime1,您当前的代码只会设置$row_ref[7]。这意味着如果$endtime1确实有值,$row_ref[7]未定义,那么在测试时会出现Use of uninitialized value $end_time1 in string eq...错误。

更改您的代码,以便将$endtime1设置为$row_ref[7](如果已定义)或NULL

    my $end_time1 = $row_ref[7] || 'NULL';

然后您可以使用现有代码:

if ($end_time1 eq "NULL")
{
    print "end_time1 is null\n";
    $dbh->do ("update service set end_time_1 = '$datetime_now' where id = $Rid");
}

$endtime2存在同样的问题,因此您可能需要进行类似的更改。

答案 1 :(得分:0)

使用defined

if ( !defined $end_time1 ) {
    print "end_time1 is null\n";
}