Search code examples
perlperl-data-structures

Perl serializing and Deserializing hash of hashes


I am trying to serialize a hash of hashes and then deserializing it to get back the original hash of hashes ..the issue is whenever i deserialize it ..it appends an autogenerated $var1 eg.

original hash

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

comes out as $VAR1 = { 'simpsons' => { 'kid' => 'bart', 'wife' => 'marge', 'husband' => 'homer' }, 'flintstones' => { 'husband' => 'fred', 'pal' => 'barney' }, };

is there any way i can get the original hash of hashes without the $var1..??


Solution

  • You've proved that Storable worked perfectly fine. The $VAR1 is part of Data::Dumper's serialisation.

    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));
    

    As you can see, both the original and the copy are identical:

    $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'
                               }
            };