我的代码在以下点失败
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 $!;
}
文件不存在,代码在第一次迭代中失败。我本来期望第一个块可以工作。
答案 0 :(得分:3)
您文件的路径很可能不存在。使用File::Path
和File::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
文件句柄或打印到它,并且很难分辨出来。
答案 1 :(得分: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 $!;
}