perl - 如果文件存在并带有通配符?

标签 perl file-exists

我需要验证文件是否存在,但文件名发生了变化。至少文件名的最后一部分是由于附加时间(hh-mm-ss)而导致的。

所以基本上,我需要查看文件 yyyy-MM-dd-hh-mm-ss 是否存在,无论 hh-mm-ss 是什么。 我正在尝试进行通配符搜索,但找不到该文件。 例如,我想检查文件 /home/httpd/doc/$user/$year/2018-08-20-* 是否存在。

是否可以使用 * 作为文件名变量?或者其他更好的方法?

我正在尝试检查文件是否存在,但使用通配符。这是我的代码:

opendir(DIR, "/home/httpd/doc/$user/2018") || die "Unable to open log/location";
while(<>){
    if($_ =~ /\/2018-08-20-\d+-\d+-\d+/) {
        print "file exists\n";
      }
 }

最佳答案

看起来您正在尝试使用 opendir-readdir 模式,它看起来像

opendir(DIR, "/home/httpd/doc/$user/2018") || die "Unable to open log/location";
foreach my $file (readdir DIR) {
    if ($file =~ /\/2018-08-20-\d+-\d+-\d+/) {
        print "file exists\n";
    }
}
closedir DIR;

但更简洁的方法(有更多边缘情况,但可能适合您的情况)是使用 glob

if (glob("/home/httpd/doc/$user/2018/2018-08-20-*")) {
    print "file exists\n";
}

关于perl - 如果文件存在并带有通配符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51923348/

相关文章:

php - 为什么这段代码这么快?

php - 检查文件是否存在于父目录(从根目录)是不可能的?

perl - 如何捕获 Perl MongoDB::Cursor 的 'recv timed out' 错误?

Perl 将字符串转换为 8 个十六进制数字组

perl - Postgres 9.4beta1 上的 otrs 子程序条目中的宽字符

c# - 区分大小写 Directory.Exists/File.Exists

php - Mac 上 file_exists() 是否区分大小写?

大量插入的 SQLite 批量提交与一次性提交

perl - 一点一点地读写文件

PHP: clearstatcache() 不工作