in reply to Dumping hash of hashes to file and back

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 $@;

Replies are listed 'Best First'.
Re^2: Dumping hash of hashes to file and back
by Herkum (Parson) on Jun 18, 2009 at 05:34 UTC
    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.