In Perl, how can I write the output of Dumper to a file?

24,769

Solution 1

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

Solution 2

Use print

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

Solution 3

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.

Share:
24,769
Prasad
Author by

Prasad

I am back

Updated on June 26, 2020

Comments

  • Prasad
    Prasad almost 4 years

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

  • Telemachus
    Telemachus almost 15 years
    I'm curious: what advantage does File::Slurp offer here?
  • Telemachus
    Telemachus almost 15 years
    For storing and restoring later, Storable is a much better idea than Data::Dumper + eval: search.cpan.org/perldoc?Storable
  • silbana
    silbana almost 15 years
    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.
  • daotoad
    daotoad almost 15 years
    Telemachus is correct. Storable, YAML, JSON, DBM::Deep or any of one million other serialization modules is a better choice than Data::Dumper + eval.
  • patz
    patz over 7 years
    @SinanÜnür how is $LOG supposed to be used. should $LOG point to a file open ($LOG, '>', 'file.txt');
  • silbana
    silbana over 7 years
    @patz $LOG is a file handle, as I clearly state up front.