我真的需要你的帮助来理解下面的 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 上将被解释为字符串值。 我在两台机器上都需要整数值。并且以后修改hash是不可能的,因为原来的代码有太多的值,必须改...
两台机器都使用 DBI 1.642 和 DBIx::Log4perl 0.26
唯一的区别是机器 1 (v5.26.1) 与机器 2 (v5.14.2) 的 perl 版本
所以最大的问题是,我怎样才能确保我总是得到散列中的整数作为结果?
2019 年 10 月 10 日更新:
为了更好地展示问题,我改进了上面的例子:
...
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::Dumper 和 JSON 具有相同的行为。正如我之前写的那样,+0 不是一个选项,因为原始哈希要复杂得多。
两台机器都使用 JSON 4.02
最佳答案
@Nick P:这就是您链接的解决方案 Why does DBI implicitly change integers to strings? , DBD::mysql 在两个系统上是不同的!所以我在机器 2 上从版本 4.020 升级到版本 4.050,现在两个系统的结果相同!整数就是整数 ;-)
所以现在两台机器上的结果是:
$VAR1 = {
'1' => 1
};
{"1":1}
谢谢!
关于mysql - Perl fetchrow_hashref 结果是不同的整数值与字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58312325/