Search code examples
perloutputperl-data-structuresdata-dumper

Dump Perl hash into new txt file every time script runs


I have a Perl script that dumps a hash into an 'output.txt' file. The problem is, every time I run this script, the same 'output.txt' file gets overwritten. How do I generate a new '.txt' file every time I run the script so that I have the results in separate files for each run?

I have something like this right now at the end of my perl script:

print Dumper( \%data );
open my $temp, '>', 'output.txt' or die $!;
print $temp Dumper \%data;
close $temp;

Solution

  • You can use a timestamp as part of the filename. I guess your script doesn't run more often than once per second.

    So instead of fixed 'output.txt' use

    my $time = time; # seconds since 1970-01-01
    my $filename = "output_$time.txt"; # output_1427737784.txt
    

    or

    use DateTime;
    my $now = DateTime->now;
    my $filename = "output_$now.txt"; # output_2015-03-30T17:49:16.txt
    

    If you need more filenames or just dislike the timestamp the File::Temp is to the rescue. It does not only create a random filename for you but also opens the file immediately (safe against dead locks) and returns a file handle.

    use File::Temp 'tempfile';
    my ($fh, $filename) = tempfile(); # replaces open()