首先,要检查文件是否存在,您需要-e 或stat(不是-f)。
其次,您将“存在但不是普通文件”结果、“找不到文件”错误和其他错误视为“找不到文件”错误。如果事情没有按您的预期工作,您应该更仔细地检查实际返回的错误是什么!
if (-e $file_path1) {
app->log->debug("\"$file_path1\" already exists.\n");
}
elsif ($!{ENOENT}) {
app->log->debug("\"$file_path1\" doesn't exist. Creating...\n");
}
else {
app->log->debug("Error stating \"$file_path1\": $!\n");
}
或
if (stat($file_path1)) {
app->log->debug("\"$file_path1\" already exists.\n");
}
elsif ($!{ENOENT}) {
app->log->debug("\"$file_path1\" doesn't exist. Creating...\n");
}
else {
app->log->debug("Error stating \"$file_path1\": $!\n");
}
如果您使用-f 是因为您还想检查它是否是一个普通文件,您可以使用以下内容:
my $rv = -f $file_path1;
if (defined($rv)) {
if ($rv) {
app->log->debug("\"$file_path1\" already exists.\n");
} else {
app->log->debug("\"$file_path1\" already exists, but isn't a plain file.\n");
}
} else {
if ($!{ENOENT}) {
app->log->debug("\"$file_path1\" doesn't exist. Creating...\n");
} else {
app->log->debug("Error stating \"$file_path1\": $!\n");
}
}
或
if (stat($file_path1)) {
if (-f _) {
app->log->debug("\"$file_path1\" already exists.\n");
} else {
app->log->debug("\"$file_path1\" already exists, but isn't a plain file.\n");
}
} else {
if ($!{ENOENT}) {
app->log->debug("\"$file_path1\" doesn't exist. Creating...\n");
} else {
app->log->debug("Error stating \"$file_path1\": $!\n");
}
}
假设你是对的,问题不是文件不存在,这些 sn-ps 中的任何一个都会得到文件不能为stated 的原因。可能是权限问题?
如果我的 sn-ps 告诉您该文件不存在,那么它确实不存在。确保您传递给stat/-e/-f 的值包含您认为的内容(例如,没有尾随空格、CR 或 LF)。如果路径是相对路径,也可能是您对当前工作目录的假设不正确。