2015-07-09 138 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++; 
    } 
}