2013-11-25 42 views
-1
失败

我的代码在低于点文件创建在Perl

my $filePath = '/opt/CUSTOM/PREPRD/IP/actions/file.conf'; 
my $udf; 
if (-e $filePath){ 
    open $udf, "<", $filePath or die $!; 
} 
else{ 
    open $udf, ">", $filePath or die $!; 
} 

该文件不存在,代码第一次迭代中失败,失败。我本来期望第一个区块能够工作。

+1

不知如何?你正在用'$!'死去,它说什么? – Quentin

+1

您确定您拥有正确的权限吗? – Cahu

+0

我改变了/tmp/file.conf的路径,它的工作,,,,,,但我希望这是在同一个目录什么应该是反馈的权限,所有的文件夹有755权限@Cahu – learner

回答

3

这很可能是您的文件的路径不存在。使用File::PathFile::Basename创建任何缺少的中间目录,这样

use strict; 
use warnings; 

use File::Path 'make_path'; 
use File::Basename 'dirname'; 

my $filePath = '/opt/CUSTOM/PREPRD/IP/actions/file.conf'; 

make_path dirname $filePath; 

my $udf; 
if (-e $filePath) { 
    open $udf, '<', $filePath or die "Unable to open conf file for input: $!" 
} 
else { 
    open $udf, '>', $filePath or die "Unable to open conf file for output: $!" 
} 

请注意,这个代码可以无论是从$udf文件中读取处理打印到它后,它会很难告诉哪个。

+0

得到了文件路径错误,但这是我想要使用的一些好东西 – learner

+0

你是什么意思*“得到的文件路径错误”*?这是从您自己的代码中复制的。 – Borodin

+0

...最后一部分/行动didnt存在....我必须创建 – learner

0
use File::Path;#abs_path, mkpath 
use File::Basename;#dirname 

unless($> == 0){ 
# are you root :: you need to be root to do write into /opt/... 
    $0 = Cwd::abs_path($0); 
    system ("sudo $0"); 
    `sudo -K`; 
    exit; 
} 

my $filePath = '/opt/CUSTOM/PREPRD/IP/actions/file.conf'; 
my $udf; 
if (-e $filePath){ 
    open $udf, "<", $filePath or die $!; 
} 
else{ 
    $path = dirname($filepath); 
    File::Path::mkpath($path); 

    open $udf, ">", $filePath or die $!; 
}