1

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;
chmod
  • 85
  • 1
  • 9

1 Answers1

2

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()
Daniel Böhmer
  • 14,463
  • 5
  • 36
  • 46
  • So when I try the first method, I get this message: Can't use string ("output_1427778835.txt") as a symbol ref while "strict refs" in use..what does it mean? – chmod Mar 30 '15 at 22:43
  • Oh my bad, sorry..was using the output file with the timestamp as the actual name of the file..That was the reason for that error message I was getting. Your suggestion works fine now! Thanks! :) – chmod Mar 30 '15 at 22:49
  • @Daniel..Another extension to the same question: Is there a way to give these output files unique names instead of having the time stamp in its name? – chmod Mar 30 '15 at 23:12