DBI 将获取的 arrayref 转换为哈希
DBI convert fetched arrayref to hash
我正在尝试编写一个程序来获取大 MySQL table,重命名一些字段并将其写入 JSON。这是我现在拥有的:
use strict;
use JSON;
use DBI;
# here goes some statement preparations and db initialization
my $rowcache;
my $max_rows = 1000;
my $LIMIT_PER_FILE = 100000;
while ( my $res = shift( @$rowcache )
|| shift( @{ $rowcache = $sth->fetchall_arrayref( undef, $max_rows ) } ) ) {
if ( $cnt % $LIMIT_PER_FILE == 0 ) {
if ( $f ) {
print "CLOSE $fname\n";
close $f;
}
$filenum++;
$fname = "$BASEDIR/export-$filenum.json";
print "OPEN $fname\n";
open $f, ">$fname";
}
$res->{some_field} = $res->{another_field}
delete $res->{another_field}
print $f $json->encode( $res ) . "\n";
$cnt++;
}
我使用了来自
Speeding up the DBI
一切似乎都很好。
我现在唯一的问题是在 $res->{some_field} = $res->{another_field}
上,行解释器抱怨说 $res
是 Not a HASH reference
。
有人能指出我的错误吗?
如果你想fetchall_arrayref
到return一个哈希引用数组,第一个参数应该是一个哈希引用。否则,arrayrefs 数组被 returned 导致 "Not a HASH reference" 错误。因此,为了 return 整行作为 hashref,只需传递一个空哈希:
$rowcache = $sth->fetchall_arrayref({}, $max_rows)
我正在尝试编写一个程序来获取大 MySQL table,重命名一些字段并将其写入 JSON。这是我现在拥有的:
use strict;
use JSON;
use DBI;
# here goes some statement preparations and db initialization
my $rowcache;
my $max_rows = 1000;
my $LIMIT_PER_FILE = 100000;
while ( my $res = shift( @$rowcache )
|| shift( @{ $rowcache = $sth->fetchall_arrayref( undef, $max_rows ) } ) ) {
if ( $cnt % $LIMIT_PER_FILE == 0 ) {
if ( $f ) {
print "CLOSE $fname\n";
close $f;
}
$filenum++;
$fname = "$BASEDIR/export-$filenum.json";
print "OPEN $fname\n";
open $f, ">$fname";
}
$res->{some_field} = $res->{another_field}
delete $res->{another_field}
print $f $json->encode( $res ) . "\n";
$cnt++;
}
我使用了来自 Speeding up the DBI 一切似乎都很好。
我现在唯一的问题是在 $res->{some_field} = $res->{another_field}
上,行解释器抱怨说 $res
是 Not a HASH reference
。
有人能指出我的错误吗?
如果你想fetchall_arrayref
到return一个哈希引用数组,第一个参数应该是一个哈希引用。否则,arrayrefs 数组被 returned 导致 "Not a HASH reference" 错误。因此,为了 return 整行作为 hashref,只需传递一个空哈希:
$rowcache = $sth->fetchall_arrayref({}, $max_rows)