【问题标题】:perl script Use of uninitialized value errorperl 脚本使用未初始化值错误
【发布时间】:2013-07-08 14:02:13
【问题描述】:

我有这个改变 MySQL 数据库数据的 perl 脚本,每次我运行它都会收到以下错误

 Use of uninitialized value in addition (+) at ./cdr_db.pl-m line 88.

查看第 80 到 88 行的代码

### archive cdr records
    $sth = $dbh2->prepare(
        "SELECT max($tablename2_archive.EventID) from $tablename2_archive")
      or die "Couldn't prepare statement: " . $dbh->errstr;
    $sth->execute()
      or die
"Database error trying to poll $tablename2_archive.EventID for archive use: "
      . $sth->errstr . "\n";
    my $nextEventID = $sth->fetchrow_array + 1;

这是完整的脚本

http://pastebin.com/4hmaS3b9

我只是不明白错误是什么。

【问题讨论】:

  • 看起来$sth->fetchrow_arrayundef。使用Data::Dumper 仔细查看$sth$sth->fetchrow_array。尝试printing out 查询(变量填写后),看看有没有问题。
  • 另外,您应该知道,由于$sth->fetchrow_array 是一个数组,当您向其添加 1 时,您是在标量上下文中调用它...
  • @JackManey:尽管它的标识符fetchrow_array 返回一个列表,它是来自数组的very different thing
  • @Borodin - [检查文档] 是的。抱歉,我通常使用 fetchrow_arrayreffetch 绑定参数。

标签: perl


【解决方案1】:

fetchrow_array 返回一个 list 值,如果没有更多行要获取,则该列表为空。

将一个添加到列表中是不好的 Perl 风格,但它具有使用列表的 last 元素的效果,这是您想要的,因为应该只有一个返回值。

就目前而言,fetchrow_array 可能返回一个空列表或以 undef 结尾的列表。此外,两者都将评估为undef。第一个最有可能,我猜你正在尝试向空表添加一条记录,而之前没有 EventID 列?

你应该写

$sth->execute;
my @row = $sth->fetchrow_array;
die "No results returned" unless @row;
my $nextEventID = $row[0] + 1;

或者绑定你正在获取的列会更好(而且更快,因为它的价值)

my $eventID;

$sth->execute;
$sth->bind_columns(\$eventID);
$sth->fetch;
die "No results returned" unless defined $eventID;
my $nextEventID = $eventID + 1;

但在进行算术运算之前,您仍然需要检查 $eventID 是否为 undef

最后。对不起,这太啰嗦了,你应该把EventIDNOT NULL,这样你就可以确定undef的值表示没有找到任何行,你应该使用MySQL AUTO_INCREMENT column 属性,这样您就不必自己计算 ID。声明看起来像

EventID INT NOT NULL AUTO_INCREMENT

当您编写 INSERT INTO 时,您只需省略该列的值。

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多