Perl fetchrow_hashref的结果是不同的整数值和字符串值



我真的需要你的帮助来理解下面的perl示例代码:

#!/usr/bin/perl
# Hashtest
use strict;
use DBI;
use DBIx::Log4perl;
use Data::Dumper;
use utf8;
if (my $dbh = DBIx::Log4perl->connect("DBI:mysql:myDB","myUser","myPassword",{
RaiseError => 1,
PrintError => 1,
AutoCommit => 0,
mysql_enable_utf8 => 1
}))
{
my $data = undef;
my $sql_query = <<EndOfSQL;
SELECT  1
EndOfSQL
my $out = $dbh->prepare($sql_query);
$out->execute() or exit(0);
my $row = $out->fetchrow_hashref();
$out->finish();
# Debugging
print Dumper($row);
$dbh->disconnect;
exit(0);
}
1;

如果我在两台机器上运行此代码,我会得到不同的结果。

机器 1 上的结果:(我需要整数值的结果(

arties@p51s:~$ perl hashTest.pl 
Log4perl: Seems like no initialization happened. Forgot to call init()?
$VAR1 = {
'1' => 1
};

机器 2 上的回复:(由于字符串值而造成麻烦的结果(

arties@core3:~$ perl hashTest.pl
Log4perl: Seems like no initialization happened. Forgot to call init()?
$VAR1 = {
'1' => '1'
};

正如您在机器 1 上看到的那样,MySQL 中的值将被解释为整数值,在机器 2 上被解释为字符串值。 我在两台机器上都需要整数值。而且以后不可能修改哈希,因为原始代码的值太多,必须更改......

两台机器都使用 DBI 1.642 和 DBIx::Log4perl 0.26

。唯一的区别是perl版本机器1(v5.26.1(与机器2(v5.14.2(

所以最大的问题是,我如何确保我总是得到哈希中的整数作为结果?

更新 10.10.2019:

为了更好地展示问题,我改进了上面的例子:

...
use Data::Dumper;
use JSON;  # <-- Inserted
use utf8;
...
...
print Dumper($row);
# JSON Output
print JSON::to_json($row)."n"; # <-- Inserted
$dbh->disconnect;
...

现在,机器 1 上的输出,最后一行是 JSON 输出:

arties@p51s:~$ perl hashTest.pl 
Log4perl: Seems like no initialization happened. Forgot to call init()?
$VAR1 = {
'1' => 1
};
{"1":1}

现在,机器 2 上的输出,最后一行是 JSON 输出:

arties@core3:~$ perl hashTest.pl
$VAR1 = {
'1' => '1'
};
{"1":"1"}

你看,Data::D umper AND JSON都有相同的行为。正如我写的bevor,+0不是一个选项,因为原始哈希要复杂得多。

两台机器都使用 JSON 4.02

@Nick P : 这就是您链接的解决方案 为什么 DBI 隐式将整数更改为字符串? ,DBD::mysql 在两个系统上是不同的!所以我在机器 2 上从 4.020 版升级到 4.050 版,现在两个系统都有相同的结果!整数就是整数;-(

所以两台机器上的结果现在都是:

$VAR1 = {
'1' => 1
};
{"1":1}

谢谢!

最新更新