2012-07-20 43 views
2

我有以下過程中,我使用同步兩個MySQL表,其中:Perl的MySQL查詢訪問超出了數組的邊界

sub sync{ 
    my %tables = (
     'sitematrix_test' => 'sitematrix_sites' 
    ); 

    while(($key, $value) = each(%tables)){ 
     print "Matching columns $key : $value\n"; 

     my @data; 
     my $query = $db->prepare(" 
      SELECT $key.* FROM $key LEFT JOIN $value ON 
      $key.site_id = $value.site_id WHERE $value.site_id IS NULL; 
     ") 
      or die "Couldn't prepare statement: " . $db->errstr; 

     $query->execute() 
      or die "Couldn't execute statement: " . $query->errstr; 

     if($query->rows == 0){ 
      print "No updates have been made for $key : $value"; 
     } 
     else{ 
      #read the matching records and print them out 
      while(@data = $query->fetchrow_array()){ 
       print "@data\n"; 
      } 
     } 

     $query->finish; 
    } 

    $db->disconnect;  
} 

它給了以下錯誤:

Use of uninitialized value $data[3] in join or string at C:/Users/souzamor/workspace/Parser/synchronizer.pl line 69. 
Use of uninitialized value $data[4] in join or string at C:/Users/souzamor/workspace/Parser/synchronizer.pl line 69. 
Use of uninitialized value $data[5] in join or string at C:/Users/souzamor/workspace/Parser/synchronizer.pl line 69. 
Use of uninitialized value $data[6] in join or string at C:/Users/souzamor/workspace/Parser/synchronizer.pl line 69. 

可能有人請解釋爲什麼它超出了數組的界限?

回答

5

您在您的數據庫中有NULL s;這些在Perl中轉換爲undef。警告來自以下行:

print "@data\n"; 

您在此處對數組進行了字符串化。例如:

perl -Mwarnings -e '@foo=(1, 2, undef, 3); print "@foo\n"' 
Use of uninitialized value $foo[2] in join or string at -e line 1. 
1 2 3 

如果你真的想字符串化整個陣列每一次打印,簡單的解決將是undef秒值進行轉換爲空字符串:

while(my @data = map { defined($_) ? $_ : '' } $query->fetchrow_array()) { 

或者,如果你不」 t需要打印全部每一行的數據,只需打印一個主鍵或者你知道的東西不會是NULL

+0

您也可以使用[*邏輯定義或*運算符'//'](http://perldoc.perl.org/perlop.html#Logical-Defined-Or),而不是使用'defined'的三元組。 – simbabque 2012-07-20 23:42:18

+0

我不認爲這是像corret:'while(my @data = map {defined?$ _:''} $ query-> fetchrow_array())' – cybertextron 2012-07-20 23:42:51

+0

@simbabque 你能證明嗎? – cybertextron 2012-07-20 23:44:14

相關問題