Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a hash that gets modified each time a program quits and must be reloaded when the program is run again.

I have been dumpin it to a file in the form of a hash and using eval() to read it back in:

%hashname = ( key => { values => "", . . . }, . . . };

Well .. i have to do this again for several other programs now, and am not looking forward to writing that again.

SO my question is this: Can I dump the hash to a file in a form that eval will read it back in, with one of perls functions (or a module even).

thanks

Replies are listed 'Best First'.
Re: dumping hashes to a file
by btrott (Parson) on Oct 23, 2000 at 23:44 UTC
    Data::Dumper is your friend.
    use Data::Dumper; open FH, ">$file" or die "Can't open $file: $!"; print FH Dumper \%hash; close FH or die "Can't close $file: $!"; ### Later... my $hashref = do $file;
Re: dumping hashes to a file
by merlyn (Sage) on Oct 23, 2000 at 23:43 UTC
Re: dumping hashes to a file
by lhoward (Vicar) on Oct 24, 2000 at 00:10 UTC
    Another option would be to use a tied hash. That way the hash on-disk would be updated in real-time as you manipulated your hash variable. This may be slower (or faster) depending on the number of elements in the hash and the number of times you access the hash:
    use DB_File; my %db; tie (%db,'DB_File','./myhashfile.dat') or die "Can't open hash file\n" +; # do stuff with %db here untie %db;
Re: dumping hashes to a file
by cianoz (Friar) on Oct 24, 2000 at 03:12 UTC
    ...or better
    use MLDBM qw(DB_File);
    this allow you to tie complex data structures.
      ... if you're willing to use MLDBM with care.

      Too many times, I've seen beginners tie %a, then wonder why setting $a{$b} works but why setting $a{$b}{$c} doesn't actually change anything on disk. Yes, it's mysterious. Too much of the underlying mechanism pokes through. For all the hassles it is, I recommend instead that you simply do your own load/save on an entire hash kept in memory.

      -- Randal L. Schwartz, Perl hacker