首页 > 解决方案 > 查找给定文件是否存在于目录中

问题描述

我想知道给定目录中是否存在文件。

我需要在temporaryPath中找到某些.txt文件,但是文件的目录需要适合模式,我需要知道给定模式中的文件是否存在,因为我认为这是查找文件的最快方法,唯一的“不确定”或“.*”路径在 a/b/c/d/e/ 和 dou/you/1.txt 之间,如果我尝试在父目录 a 下使用 Find::File 正常查找/b/c/d/e/,大约需要 10 分钟,并且有可能我在数组中存储了不需要的路径,因为 1.txt 也存在于子目录中。

例如想要特定的目录

a/b/c/d/e/f/g/h/dou/you/1.txt
a/b/c/d/e/k/l/m/dou/you/1.txt

a/b/c/d/e/k/l/m/wanna/play/2.txt
a/b/c/d/e/z/x/c/wanna/play/2.txt

a/b/c/d/e/f/g/h/with/me/3.txt
a/b/c/d/e/z/x/c/with/me/3.txt

Perl

use strict;
use warnings;

my @temporaryPath = qw(
    dou/you/1.txt
    wanna/play/2.txt
    with/me/3.txt
    like/play/4.txt
    anything/really/5.txt
);

foreach my $temporaryList ( @temporaryPath ) {

    my $dir = "a/b/c/d/e/" . "*" . "/$temporaryList";

    if ( -e $dir ) {
        print " exist :) $temporaryList\n";
    }
    else {
        print " not exist :( $temporaryList\n";
    }
}

我之所以使用.*in$dir是因为路径完整路径之间有很多不同的目录,例如f/g/h,k/l/mz/x/c.

结果是这样的

not exist :( dou/you/1.txt
not exist :( wanna/play/2.txt
not exist :( with/me/3.txt
not exist :( like/play/4.txt
not exist :( anything/really/5.txt

意思是$dir看不懂a/b/c/d/e/.*/

有什么办法吗?

标签: perldirectoryfile-exists

解决方案


听起来你需要这个 File::Globstar模块。它实现了等效的 shell globstar扩展,允许**模式中的两个星号匹配任何字符串,包括路径分隔符

它可能看起来像这样

use strict;
use warnings 'all';
use feature 'say';

use File::Globstar 'globstar';

my @paths = qw{
    dou/you/1.txt
    wanna/play/2.txt
    with/me/3.txt
    like/play/4.txt
    anything/really/5.txt
};

for my $path ( @paths ) {

    say for globstar "a/b/c/d/e/**/$path;
}

推荐阅读