我真的需要您的帮助来理解以下 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
唯一的区别是 perl 版本机器 1 (v5.26.1) 与机器 2 (v5.14.2)
所以最大的问题是,我怎样才能确保我总是得到哈希中的整数作为结果?
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