mysql - 抛出“不是数组引用”错误

标签 mysql perl

我正在编写一个 Perl 脚本,该脚本旨在处理一个 API,该 API 返回有关我从 MySQL 中提取的一组 URL 的指标,然后将这些指标发布回另一个表中。目前这段代码:

my $content = $response->content;

my $jsontext = json_to_perl($content);

my $adsql = 'INSERT INTO moz (url_id,page_authority,domain_authority,links,MozRank_URL,MozRank_Subdomain,external_equity_links) VALUES (?,?,?,?,?,?,?)';
my $adrs = $db->prepare( $adsql );

my $adsql2 = 'UPDATE url 
SET moz_crawl_date = NOW()
where url_id = ?;';
my $adrs2 = $db->prepare( $adsql2 );

my $currentUrlId = 0;

foreach my $row (@$jsontext){
    $adrs->execute($url_ids[$currentUrlId], $row->{'fmrp'}, $row->{'upa'}, $row->{'pda'}, $row->{'uid'}, $row->{'umrp'}, $row->{'ueid'});# || &die_clean("Couldn't execute\n$adsql\n".$db->errstr."\n" );
    $adrs2->execute($url_ids[$currentUrlId]);
    $currentUrlId++;
}

抛出此错误:

Not an ARRAY reference at ./moz2.pl line 124.

这是第 124 行:

foreach my $row (@$jsontext){

这整段代码都在一个 while 循环中。实际上,我能够在脚本失败之前迭代几次并填充我的 MySQL 表(从技术上讲,该程序可以工作,但我不想只在其中留下错误)。

有人有什么建议吗?

最佳答案

Perl 给了你正确的答案

不是 ARRAY 引用:@$jsontext

您正在取消引用 $jsontext(它是 json_to_perl(string) 的结果)对数组的引用。 但是 json_to_perl() 没有返回 arrayref。

json_to_perl 似乎来自此 API:http://search.cpan.org/~bkb/JSON-Parse-0.31/lib/JSON/Parse.pod#json_to_perl 根据文档,它返回 arrayref 或 hashref。

显然它确实在您的情况下返回了 hashref,因此您必须添加逻辑来处理 HASH 情况。这似乎是单行。

if (ref $jsontext eq 'HASH') {
  # seems to be a single row
  $adrs->execute($url_ids[$currentUrlId], $jsontext->{'fmrp'}, $jsontext->'upa'}, $jsontext->'pda'}, $jsontext->'uid'}, $jsontext->'umrp'}, $jsontext->'ueid'});# || &die_clean("Couldn't execute\n$adsql\n".$db->errstr."\n" );
  $adrs2->execute($url_ids[$currentUrlId]);
  $currentUrlId++;
} elsif (ref $jsontext eq 'ARRAY') {
  foreach my $row (@$jsontext){
    $adrs->execute($url_ids[$currentUrlId], $row->{'fmrp'}, $row->{'upa'}, $row->{'pda'}, $row->{'uid'}, $row->{'umrp'}, $row->{'ueid'});# || &die_clean("Couldn't execute\n$adsql\n".$db->errstr."\n" );
    $adrs2->execute($url_ids[$currentUrlId]);
    $currentUrlId++;
  }
}

关于mysql - 抛出“不是数组引用”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31330141/

相关文章:

c# - subsonic 3.0.0.3 似乎没有更新数据库

perl - 我想更改我的默认 perl

perl - Perl 中的递归搜索?

perl - 拆分后存储 token

perl - 如何动态加载 Perl 模块并使用它们的功能?

mysql - 如何找到列中两行之间的时间差

java - 为什么 Hibernate 不为 MySQL 创建数据库?

php - SQL QUERY 没有得到我期望的结果

mysql - 如何仅获取 'In' 状态为 'current date' 的某些列的计数

perl - 如何为散列制造病态 key ?