9

How can I make Data::Dumper write a dump into a file?

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
joe
  • 34,529
  • 29
  • 100
  • 137

3 Answers3

26

Don't forget that you can specify the file handle to print to as in

print $LOG Dumper( \%some_complex_hash );

or use File::Slurp:

write_file 'mydump.log', Dumper( \%some_complex_hash );

Further thoughts: You might want to get into the habit of using:

warn Dumper( \%some_complex_hash );

and redirecting standard error to a file when you invoke your script (how you do this depends on the shell). For example:

 C:\Temp> sdf.pl 2>dump
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
8

The question is a bit unclear, but are you looking for something like this?

open my $FH, '>', 'outfile';
print $FH Dumper(\%data);
close $FH;

You can restore the data later by using eval.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Michiel Buddingh
  • 5,783
  • 1
  • 21
  • 32
  • 6
    For storing and restoring later, Storable is a much better idea than Data::Dumper + eval: http://search.cpan.org/perldoc?Storable – Telemachus Jul 14 '09 at 16:37
  • 1
    Telemachus is correct. Storable, YAML, JSON, DBM::Deep or any of one million other serialization modules is a better choice than Data::Dumper + eval. – daotoad Jul 14 '09 at 17:01
8

Use print

print FILE Data::Dumper->Dump($object);
dsm
  • 10,263
  • 1
  • 38
  • 72