我有以下过程,我用它来同步两个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.
有人可以解释为什么它超出了数组的范围?
答案 0 :(得分:5)
您的数据中有NULL
来自数据库;这些在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() ) {
或者,如果您不需要为每一行打印所有数据,只需打印一个您知道不会是NULL
的主键或其他内容。