views:

710

answers:

3

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

+10  A: 

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
I'm curious: what advantage does File::Slurp offer here?
Telemachus
If all I want is to dump a complex data structure to a file for debugging purposes, it is more self contained than open / print / close: no filehandles or error messages to mess with.
Sinan Ünür
+4  A: 

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.

Michiel Buddingh'
For storing and restoring later, Storable is a much better idea than Data::Dumper + eval: http://search.cpan.org/perldoc?Storable
Telemachus
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
+5  A: 

Use print

print FILE Data::Dumper->Dump($object);
dsm