Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..??

like image 250
user1547285 Avatar asked Jul 24 '12 01:07

user1547285


2 Answers

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'
                           }
        };
like image 194
ikegami Avatar answered Oct 14 '22 12:10

ikegami


If you set $Data::Dumper::Terse to 1, then Data::Dumper will try to skip these variable names (but the result could sometimes be no longer parseable by eval).

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

becomes now:

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

Maybe something like JSON or YAML would be better for your purpose?

like image 42
Sebastian Stumpf Avatar answered Oct 14 '22 13:10

Sebastian Stumpf