5

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

原始哈希

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

出来为 $VAR1 = { 'simpsons' => { 'kid' => 'bart', 'wife' => 'marge', 'husband' => 'homer' }, 'flintstones' => { 'husband' => '弗雷德', '朋友' => '巴尼' }, };

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

4

2 回答 2

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'
                           }
        };
于 2012-07-24T02:16:57.917 回答
3

如果您设置$Data::Dumper::Terse1,则 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这样的东西更适合您的目的?

于 2012-07-24T02:33:24.340 回答