如何检查 Perl 中是否存在文件? [英] How can I check if a file exists in Perl?

查看:92
本文介绍了如何检查 Perl 中是否存在文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相对路径

   $base_path = "input/myMock.TGZ";

myMock.TGZ 是位于输入文件夹中的文件名.文件名可以更改.但是路径总是存储在 $base_path 中.

myMock.TGZ is the file name located in input folder. The filename can change. But the path is always stored in $base_path.

我需要检查文件是否存在于$base_path.

I need to check if the file exists in $base_path.

推荐答案

使用 -e 文件测试运算符测试给定路径中是​​否存在 something.

Test whether something exists at given path using the -e file-test operator.

print "$base_path exists!\n" if -e $base_path;

但是,此测试可能比您预期的更广泛.如果该路径中存在纯文件,则上面的代码将生成输出,但它也会为目录、命名管道、符号链接或更奇特的可能性触发.查看文档了解详情.

However, this test is probably broader than you intend. The code above will generate output if a plain file exists at that path, but it will also fire for a directory, a named pipe, a symlink, or a more exotic possibility. See the documentation for details.

鉴于您的问题中 .TGZ 的扩展名,您似乎希望使用 普通文件 而不是替代文件.-f 文件测试运算符询问路径是否通向普通文件.

Given the extension of .TGZ in your question, it seems that you expect a plain file rather than the alternatives. The -f file-test operator asks whether a path leads to a plain file.

print "$base_path is a plain file!\n" if -f $base_path;

perlfunc 文档涵盖了一长串 Perl 的文件测试操作符,其中涵盖了你在实践中会遇到很多情况.

The perlfunc documentation covers the long list of Perl's file-test operators that covers many situations you will encounter in practice.

  • -r
    文件可通过有效的 uid/gid 读取.
  • -w
    文件可由有效的 uid/gid 写入.
  • -x
    文件可由有效的 uid/gid 执行.
  • -o
    文件归有效 uid 所有.
  • -R
    文件可由真实 uid/gid 读取.
  • -W
    文件可由真实 uid/gid 写入.
  • -X
    文件可由真实 uid/gid 执行.
  • -O
    文件归真实 uid 所有.
  • -e
    文件存在.
  • -z
    文件大小为零(为空).
  • -s
    文件具有非零大小(以字节为单位返回大小).
  • -f
    文件是一个普通文件.
  • -d
    文件是一个目录.
  • -l
    文件是一个符号链接(如果文件系统不支持符号链接,则为 false).
  • -p
    File 是一个命名管道 (FIFO),或者 Filehandle 是一个管道.
  • -S
    文件是一个套接字.
  • -b
    文件是块特殊文件.
  • -c
    文件是字符特殊文件.
  • -t
    文件句柄被打开到一个 tty.
  • -u
    文件设置了 setuid 位.
  • -g
    文件设置了 setgid 位.
  • -k
    文件设置了粘滞位.
  • -T
    文件是 ASCII 或 UTF-8 文本文件(启发式猜测).
  • -B
    文件是一个二进制"文件(与 -T 相反).
  • -M
    脚本开始时间减去文件修改时间,以天为单位.
  • -A
    访问时间相同.
  • -C
    inode 更改时间相同(Unix,其他平台可能有所不同)

这篇关于如何检查 Perl 中是否存在文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆