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

Dear Monks,
How can I use Data::Dumper to write/read hash of hashes to/from the file.
If not there should be a different simple way.
  • Comment on Dumping hash of hashes to file and back

Replies are listed 'Best First'.
Re: Dumping hash of hashes to file and back
by shmem (Chancellor) on Jun 18, 2009 at 00:52 UTC

    What part of the Data::Dumper manual page is unclear?

    write:

    use Data::Dumper; my %h = ( foo => 1, bar => { quux => 2, frob => 3, }, ); open my $fh, '>', 'hash.pl' or die "nope: $!"; print $fh Dumper(\%h); close $fh or die "fasten seat belts. Last orders: $!";

    retrieve:

    my %h = %{ require 'hash.pl' }; die "read hash dinn' work: $@" if $@;
      my %h = %{ require 'hash.pl' };

      Interesting, I did not know about this trick. It is cleaner than doing an eval on the file text.

        Cleaner...?

        Just be aware that require only loads the file the first time you call it. If you need to load up the hash more than once, %{ require 'hash.pl' }; may not be such a good idea. The second time you call it, require sees that the file is already loaded and will return 1, which isn't a hash reference at all. If you have strict or warnings turned on (and you should), Perl will kindly inform you of the problem by generating a warning:Can't use string ("1") as a HASH ref while "strict refs" in use at ....

        If you really want to load a file full of Perl code and set a variable in one step, use do instead. Like require it returns the value of the final statement in the file, but it doesn't have the reload problem. This can be safely reused:

        %{do 'hash.pl'}

        Best, beth

        It is essentially the same. All file inclusion mechanisms are based on string eval, as perldoc -q require tells.

Re: Dumping hash of hashes to file and back
by jethro (Monsignor) on Jun 18, 2009 at 00:25 UTC
Re: Dumping hash of hashes to file and back
by GrandFather (Saint) on Jun 18, 2009 at 05:21 UTC

    If you want human readable then YAML (or one of the many other implementations) may be of interest.


    True laziness is hard work