Perl序列化和反序列化哈希的散列

时间:2012-07-24 01:49:14

标签: perl perl-data-structures

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

原始哈希

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

出来了      $ VAR1 = {           'simpsons'=> {                           'kid'=> “巴特”,                           '妻子'=> “玛吉”,                           '丈夫'=> “本垒打”                         },           'flintstones'=> {                              '丈夫'=> “弗雷德”,                              'pal'=> “巴尼”                            }, };

有没有什么方法可以得到没有$ var1的哈希的原始哈希值???

2 个答案:

答案 0 :(得分:9)

你已经证明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'
                           }
        };

答案 1 :(得分:3)

如果将$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之类的内容可能会更适合您的目的吗?

相关问题