如果日志文件不存在,请在Perl中创建一个目录

use*_*927 12 directory perl mkdir

我有一个Perl脚本,它需要一些参数.它执行如下:

exec myscript.pl --file=/path/to/input/file --logfile=/path/to/logfile/logfile.log
Run Code Online (Sandbox Code Playgroud)

我在脚本中有以下行:

open LOGFILE, ">>$logFilePath" or die "Can't open '$logFilePath': $!\n";
Run Code Online (Sandbox Code Playgroud)

$logfilePath从命令线.如果有一个路径,/ path /到/ logfile /,但没有logfile.log,它只是创建它(这是所需的操作).但是,如果没有这样的路径,它就无法启动.如果脚本在运行脚本之前不存在,如何创建日志文件的路径?

Ala*_*avi 22

假设您logfile.log在变量中有日志文件的路径(可能包含或不包含文件名:) $full_path.然后,您可以根据需要创建相应的目录树:

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";
}
Run Code Online (Sandbox Code Playgroud)

现在,$full_path将包含logfile.log文件的完整路径.还将创建路径中的目录树.


dan*_*111 7

更新:正如Dave Cross指出的那样,mkdir只创建一个目录.因此,如果您想一次创建多个级别,这将不起作用.

使用Perl的mkdir命令.例:

#Get the path portion only, without the filename.
if ($logFilePath =~ /^(.*)\/[^\/]+\.log$/)
{
    mkdir $1 or die "Error creating directory: $1";
}
else
{
    die "Invalid path name: $logFilePath";
}
Run Code Online (Sandbox Code Playgroud)

使用perl自己的函数比运行unix命令更可取.

编辑:当然,您还应该先检查目录是否存在.使用-e检查是否存在的东西.将其添加到上面的代码中:

#Get the path portion only, without the filename.
if ($logFilePath =~ /^(.*)\/[^\/]+\.log$/)
{
    if (-e $1) 
    {
        print "Directory exists.\n";
    }
    else
    {
        mkdir $1 or die "Error creating directory: $1";
    }
}
else
{
    die "Invalid path name: $logFilePath";
}
Run Code Online (Sandbox Code Playgroud)

  • `mkdir()`的问题是,一次只能创建一个级别的目录.如果你可能会创建多个级别(通常是这样),那么File :: Path的`make_path()`是一个更好的建议. (2认同)