2013-11-25 43 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 $!; 
}