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

问题描述 投票:1回答:1

我真的需要您的帮助来理解以下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上的结果:(结果i必须为整数)

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 :: Dumper和JSON的行为相同。正如我所写的,+ 0不是一个选择,因为原始哈希值要复杂得多。

两台机器都使用JSON 4.02

mysql database perl dbi hashref
1个回答
2
投票

@@尼克P:这就是您链接的解决方案Why does DBI implicitly change integers to strings?,两个系统上的DBD :: mysql都不一样!因此,我在计算机2上将其从版本4.020升级到了版本4.050,现在两个系统都具有相同的结果!而整数就是整数;-)

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

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

谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.