Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a directory in Perl for a logfile if it does not exist

I have a Perl script which takes a few arguments. It is executed like this:

exec myscript.pl --file=/path/to/input/file --logfile=/path/to/logfile/logfile.log

I have the following line in the script:

open LOGFILE, ">>$logFilePath" or die "Can't open '$logFilePath': $!\n";

Where $logfilePath is taken from the command line. If there is a path, /path/to/logfile/, but no logfile.log, it just creates it (which is the desired action). However, it fails to start if there is no such path. How can I make the script create the path for the logfile, if it does not exist prior to running the script?

like image 676
user1546927 Avatar asked Aug 21 '12 08:08

user1546927


Video Answer


1 Answers

Suppose you have the path to the logfile (which may or may not include the filename: logfile.log) in the variable $full_path. Then, you can create the respective directory tree if needed:

use File::Basename qw( fileparse );
use File::Path qw( make_path );
use File::Spec;

my ( $logfile, $directories ) = fileparse $full_path;
if ( !$logfile ) {
    $logfile = 'logfile.log';
    $full_path = File::Spec->catfile( $full_path, $logfile );
}

if ( !-d $directories ) {
    make_path $directories or die "Failed to create path: $directories";
}

Now, $full_path will contain the full path to the logfile.log file. The directory tree in the path will have also been created.

like image 61
Alan Haggai Alavi Avatar answered Sep 30 '22 18:09

Alan Haggai Alavi