【问题标题】:File creation failing in PerlPerl 中的文件创建失败
【发布时间】:2013-12-10 03:00:39
【问题描述】:

我的代码在以下点失败

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 $!;
}

文件不存在,代码在第一次迭代中失败。我本来希望第一个块可以工作。

【问题讨论】:

  • 失败怎么办? $! 你快死了,它说什么?
  • 你确定你有正确的权限吗?
  • 我将路径更改为 /tmp/file.conf 并且它有效,,,,,,但我希望它位于同一个目录中 flders 的权限应该是什么,所有文件夹都有755 权限@Cahu
  • 这段代码看起来没问题,除非第一个 open 因为权限问题而失败。您是否清楚 $udf 文件句柄将打开 要么 用于读取 用于写入,具体取决于文件是否存在?这意味着您可以打印到文件句柄或从中读取,但您必须编写更多 if 语句才能发现哪个。我认为您更有可能只想要一个可写入的打开(第二个open 语句)或追加(使用'&gt;&gt;' 的模式)。
  • @learner 您需要对该文件夹的写入权限才能允许在else 块中创建文件。

标签: perl unix file-permissions


【解决方案1】:

您的文件的路径很可能不存在。使用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文件句柄中读取打印到它,但很难分辨是哪个。 p>

【讨论】:

  • 文件路径错误,但这是我想要使用的一些好东西
  • 你是什么意思“文件路径错误”?这是从您自己的代码中复制而来的。
  • 啊,好吧。致电make_path 将为您完成。这就是我回答的重点。如果您有所需的解决方案,请通过接受答案将您的问题标记为已解决。
【解决方案2】:
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 $!;
}   

【讨论】:

    猜你喜欢
    • 2011-02-13
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    相关资源
    最近更新 更多