解决此错误的正确方法是什么无法在未定义的值上调用方法“fetchrow_array”

时间:2013-10-03 12:50:32

标签: perl

下面是我用于在crontab上运行脚本的perl代码

if($enable_family_members==0)
{
  my $sql="select name from test where testid IN (". join(',',  @set) . ')';
  my $sth = $dbh->prepare($sql);
  $sth->execute or die "SQL Error: $DBI::errstr\n"; 
}

while (my ($name)=$sth->fetchrow_array())
{
  print "name: $name";
}  

当我尝试运行此脚本时,出现错误Can't call method "fetchrow_array" on an undefined value at line 9。当我尝试在$ sth中使用our 关键字而不是my 关键字时,我不会收到错误消息。解决此错误的正确方法是什么。

1 个答案:

答案 0 :(得分:3)

您的$sth变量仅在if块内可见。尝试:

if($enable_family_members==0) {
    my $sql="select name from test where testid IN (". join(',',  @set) . ')';
    my  $sth = $dbh->prepare($sql);
    $sth->execute or die "SQL Error: $DBI::errstr\n"; 
    while (my ($name)=$sth->fetchrow_array()) {
        print "name: $name";
    }
}