【问题标题】:Perl serializing and Deserializing hash of hashesPerl 序列化和反序列化散列的散列
【发布时间】:2012-07-22 07:22:24
【问题描述】:

我正在尝试序列化哈希哈希,然后反序列化它以取回哈希的原始哈希。问题是每当我反序列化它时......它会附加一个自动生成的 $var1 例如。

原始哈希

%hash=(flintstones => {
    husband   => "fred",
    pal       => "barney",
},
jetsons => {
    husband   => "george",
    wife      => "jane",
    "his boy" => "elroy",  
},
);

出来 $VAR1 = { “辛普森一家” => { '孩子' => '巴特', '妻子' => '玛吉', '丈夫' => '本垒打' }, '燧石' => { '丈夫' => '弗雷德', '朋友' => '巴尼' }, };

有没有什么方法可以在没有 $var1.. 的情况下获得原始哈希值??

【问题讨论】:

  • $VAR1 未添加。它是序列化的一部分。是什么让您认为反序列化后会给出不同的哈希值?你如何反序列化它?
  • 就个人而言,我会使用 JSON::XS 序列化为 JSON。 Data::Dumper 是一个调试工具,不是一个好的序列化器。尤其是默认选项。
  • 我已经使用 Freeze/thaw 进行了序列化/反序列化...我需要获取原始哈希,以便可以对其进行一些计算...
  • 您提供的输出是 Data::Dumper 创建的序列化。 $VAR1 是 Data::Dumper 序列化的一部分。您刚刚证明 Storable 工作正常。

标签: perl perl-data-structures


【解决方案1】:

您已经证明 Storable 运行良好。 $VAR1 是 Data::Dumper 序列化的一部分。

use Storable     qw( freeze thaw );
use Data::Dumper qw( Dumper );

my %hash1 = (
   flintstones => {
      husband  => "fred",
      pal      => "barney",
   },
   jetsons => {
      husband  => "george",
      wife     => "jane",
     "his boy" => "elroy",  
   },
);

my %hash2 = %{thaw(freeze(\%hash1))};

print(Dumper(\%hash1));
print(Dumper(\%hash2));

如您所见,原件和副本都是相同的:

$VAR1 = {
          'jetsons' => {
                         'his boy' => 'elroy',
                         'wife' => 'jane',
                         'husband' => 'george'
                       },
          'flintstones' => {
                             'husband' => 'fred',
                             'pal' => 'barney'
                           }
        };
$VAR1 = {
          'jetsons' => {
                         'his boy' => 'elroy',
                         'wife' => 'jane',
                         'husband' => 'george'
                       },
          'flintstones' => {
                             'husband' => 'fred',
                             'pal' => 'barney'
                           }
        };

【讨论】:

    【解决方案2】:

    如果您将$Data::Dumper::Terse 设置为1,则Data::Dumper 将尝试跳过这些变量名(但结果有时可能无法再被eval 解析)。

    use Data::Dumper;
    $Data::Dumper::Terse = 1;
    print Dumper \%hash;
    

    变成现在:

    {
      'jetsons' => {
                     'his boy' => 'elroy',
                     'wife' => 'jane',
                     'husband' => 'george'
                   },
      'flintstones' => {
                         'husband' => 'fred',
                         'pal' => 'barney'
                       }
    }
    

    也许像 JSONYAML 这样的东西更适合您的目的?

    【讨论】:

      猜你喜欢
      • 2017-03-21
      • 2014-07-28
      • 2011-03-13
      • 1970-01-01
      • 2014-05-19
      • 1970-01-01
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多