Friday, January 18, 2013

saving perl data structure to the file and reading it back

We can save the data structure like hashes, arrays, and their combinations to local file and read them back, which can be called as serializing and deserialzing the DS in perl.

Example 1: writing hash to a file and red it back

save_and_read_perl_ds_to_file.pl


#!/usr/bin/perl
use Data::Dumper;

system("clear");

#sample hash
my %h1 = (
           k1 => 'v1',
           k2 => 'v2',
           k3 => 'v3'
         );

print "before writing to a file:\n";
print Dumper(\%h1);

#write perl hash to a file using data dumper

open  FH, '>', 'ds_file.csv' or die "cant open file";
print FH Data::Dumper->Dump([\%h1]); #NOTE [ %h1 ] unlike print Dumper(\%h1);
close FH;


#read the hash from file
open FH, 'ds_file.csv' or die "$!";

local $/;  #slurp mode http://perl-savvy.blogspot.in/2013/01/perl-slurp-mode.html
$hashref = eval <FH>;

close FH;

print "\nafter writing and reading back again :\n ";
print Dumper($hashref);

-----------------------------------------------------------------------


ds_file.csv


$VAR1 = {
          'k2' => 'v2',
          'k1' => 'v1',
          'k3' => 'v3'
        };



As you can see the contents of file where in we dumped the hash, in the perl file save_and_read_perl_ds_to_file.pl, we do eval on file_handle of this file, which returns the hash reference.






No comments:

Post a Comment