2015-07-09 132 views
0

我正在编写一个Perl脚本,它意味着处理一个API,它将返回有关我从MySQL提取的一组URL的度量标准,然后将这些度量标准发回到不同的表中。目前这一段代码:'不是ARRAY参考'错误抛出

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表(从技术上讲,程序可以工作,但我不想只留下一个错误)。

有人有什么建议吗?

+0

当你得到这个错误时'$ content'的值是多少?该错误意味着它不是JSON数组。 – Barmar

+0

换行符,不只是一个建议。 –

+0

要么是散列,要么是看起来像散列的字符串。当我打印出来时,它看起来像这样:[{“fmrp”:6.182095114661029,“fmrr”:8.22438062351392e-08,“pda”:58.91591252161899,“ueid”:5831,“uid”:480143,“umrp”:6.63361336728684 ,“umrr”:1.869832885935372e-08,“upa”:65.70993919657755}] –

回答

0

的Perl给你正确的答案

Not an ARRAY reference: @$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 ,其根据该文档要么一个数组引用或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++; 
    } 
}