Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I wanted to crete a file to a directory with a timestamp. I am able to create a directory, but i am unable to open the file.If the file is not present,it should automatically create it right?
my $resultfile="test-result-".`date +%d_%b_%H-%M`; $dir="results"; `mkdir ./results/$resultfile`; $path="./results/$resultfile"; ; open(F, ">> $path/result.log") || die "cannot create resultfile:$!\n";
This prints the result as unable to open the file.... How can i solve it???

Replies are listed 'Best First'.
Re: Creating result file with time stamp
by Utilitarian (Vicar) on Jun 17, 2009 at 07:51 UTC
    Perl provides all the directory and date info you require. The following works for me, as well as testing for existence, in anything other than a command line hack such as below, you should also test the return value of the mkdir commands.

    On a Unix system you cannot create a whole path with a mkdir command, unless you supply the -p option, but as I said, when Perl provides the means to create directories and test the outcome of the request, why spawn a shell sub process ;)

    utilitarian@busybox:~/tmp/test$ perl -e ' $time=localtime; ($day,$month,$date,$time,$year)=split(/ /,$time); $stamp=$year."_".$month."_".$date; $dir="result_".$stamp; mkdir "results" if ( ! -d "results"); $path="results/$dir"; mkdir "$path" if ( ! -d "$path"); open (F,">>", "$path/results.log"); print F "This file exists\n"; close(F);' utilitarian@busybox:~/tmp/test$ ls results/ result_2009_Jun_17 utilitarian@busybox:~/tmp/test$ ls results/result_2009_Jun_17/ results.log utilitarian@busybox:~/tmp/test$ cat results/result_2009_Jun_17/resul +ts.log This file exists
Re: Creating result file with time stamp
by Anonymous Monk on Jun 17, 2009 at 06:15 UTC
    This prints the result as unable to open the file.... How can i solve it???

    Cut/paste the exact error message

      cannot create resultfile:No such file or directory
        That means the directory 'results' doesn't exist

        Other problem

        `mkdir ./results/$resultfile`; $path="./results/$resultfile";
        "/results/$resultfile" can't be both a directory and a file.
        $ md temp $ echo >temp Access is denied.
Re: Creating result file with time stamp
by bichonfrise74 (Vicar) on Jun 17, 2009 at 17:37 UTC
    Is this what you are looking for?
    #!/usr/bin/perl use strict; chomp( my $date = `date +%d_%b_%H-%M` ); my $dir = "/tmp"; my $result_file = "test-result-$date"; mkdir "$dir/$result_file" if ( !-d "$dir/$result_file" ); open( my $fh, ">", "$dir/$result_file/results.log" ) or die "Cannot create file - $!\n";